import os
os.environ['KERAS_BACKEND']='tensorflow'
import numpy as np
from keras.applications.vgg16 import VGG16
from keras.applications.vgg16 import preprocess_input
from keras.preprocessing import image
from keras.utils.data_utils import get_file
import ssl
ssl._create_default_https_context = ssl._create_unverified_context # 下载模型的时候不想进行ssl证书校验
# !export TF_CPP_MIN_LOG_LEVEL=2 # 屏蔽警告信息 (这是在jupyter中执行的shell命令,可以去掉这行不影响结果)
# 初始化VGG16模型 include_top=False 是指不保留顶层的3个全连接网络层
model = VGG16(weights='imagenet', include_top=False)
# # 创建模型
# # Create model.
# model = Model(inputs, x, name='vgg16')
#
# # 加载权重
# # load weights
# if weights == 'imagenet':
# if include_top:
# weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels.h5',
# WEIGHTS_PATH,
# cache_subdir='models')
# else:
# weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
# WEIGHTS_PATH_NO_TOP,
# cache_subdir='models')
# model.load_weights(weights_path)
WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5'
def get_feature(path):
"""
VGG16模型抽取图片特征
"""
# 图片转成PIL的Image对象,并且对图片做了缩放
img = image.load_img(path, target_size=(224, 224))
# 图片转成矩阵、并扩充了维度、最后是预处理
predict_img = preprocess_input(np.expand_dims(image.img_to_array(img),0))
# 丢入vgg16网络做特征抽取,最后返回特征并展平成一维向量方便计算余弦相似度,flatten是numpy.ndarray.flatten的一个函数,即返回一个一维数组。
return model.predict(predict_img).flatten()
def cos_sim(a, b):
"""
计算两个向量之间的余弦相似度
"""
a = np.mat(a)
b = np.mat(b)
return float(a * b.T) / (np.linalg.norm(a) * np.linalg.norm(b))
if __name__ == '__main__':
image_path = ['D:\\9.jpg', 'D:\\10.jpg']
ft1, ft2 = [get_feature(p) for p in image_path]
print(cos_sim(ft1, ft2))
python 图片相似度计算
最新推荐文章于 2024-09-12 19:51:15 发布