赞
踩
VGG16是一种深度学习模型,它属于卷积神经网络(Convolutional Neural Networks, CNNs)的一种,由牛津大学的视觉几何组(Visual Geometry Group)开发。这个模型在图像识别领域表现出色,尤其是在2014年的ImageNet挑战赛中。
VGG16模型包含了16个隐藏层,其中13个卷积层和3个全连接层。这些卷积层和全连接层之间还穿插着激活函数(ReLU)和池化层(MaxPooling)。VGG16特别之处在于它仅使用了很小的卷积核(3x3),叠加多层卷积层来增加网络的深度,从而捕获更高级的图像特征。
假设我们有两张猫的图片,一张是黑白的,另一张是彩色的。
尽管这两张猫的图片在颜色上有所不同,但如果它们在结构和内容上相似,那么经过VGG16模型提取的特征向量也将会是相似的,因此我们可以判断这两张图片在视觉上是相似的。
总的来说,利用VGG16等深度学习模型进行图片对比的基础在于模型能够从图像中提取出高层次、抽象的特征,并将这些特征用于计算图片之间的相似度。
- from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
- from tensorflow.keras.preprocessing import image
- from tensorflow.keras.models import Model
- import numpy as np
-
- # 加载预训练的VGG16模型,不包括最后的全连接层
- base_model = VGG16(weights='imagenet', include_top=False)
-
- # 定义新的模型,将原VGG16模型的输出直接作为新模型的输出
- model = Model(inputs=base_model.input, outputs=base_model.output)
- def extract_features(img_path, model):
- """从指定路径的图像中提取特征"""
- # 加载图像,调整大小为224x224,VGG16模型要求的输入大小
- img = image.load_img(img_path, target_size=(224, 224))
-
- # 将PIL图像转换为numpy数组,并添加一个维度表示批大小
- img_array = image.img_to_array(img)
- img_array = np.expand_dims(img_array, axis=0)
-
- # 预处理图像
- img_array = preprocess_input(img_array)
-
- # 通过模型获取图像的特征
- features = model.predict(img_array)
-
- # 扁平化特征使其成为一维数组
- flatten_features = features.flatten()
-
- # 归一化特征向量以比较它们的相似性
- normalized_features = flatten_features / np.linalg.norm(flatten_features)
-
- return normalized_features

- def calculate_similarity(features1, features2):
- """计算两组特征之间的相似度"""
- similarity = np.dot(features1, features2)
- return similarity
- # 图片路径
- img_path1 = 'C:/Users/Administrator/Desktop/temp/img1.jpg'
- img_path2 = 'C:/Users/Administrator/Desktop/temp/img2.jpg'
-
- # 提取特征
- features1 = extract_features(img_path1, model)
- features2 = extract_features(img_path2, model)
-
- # 计算相似度
- similarity = calculate_similarity(features1, features2)
- print(f"Similarity: {similarity}")
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。