使用 VGG16 模型从图像中提取特征并计算它们之间的相似度分数。 我们首先导入必要的库,初始化 VGG16 模型,并定义用于加载和处理图像、计算其嵌入以及计算相似性分数的函数。
import numpy as np
from PIL import Image
from tensorflow.keras.preprocessing import image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from keras.applications.vgg16 import VGG16
from sklearn.metrics.pairwise import cosine_similarity
vgg16 = VGG16(weights='imagenet', include_top=False,
pooling='max', input_shape=(224, 224, 3))
# print the summary of the model's architecture.
vgg16.summary()
for model_layer in vgg16.layers:
model_layer.trainable = False
#输入图像预处理
def load_image(image_path):
"""
-----------------------------------------------------
Process the image provided.
- Resize the image
-----------------------------------------------------
return resized image
"""
input_image = Image.open(image_path)
resized_image = input_image.resize((224, 224))
return resized_image
#、输入图像嵌入向量计算
def get_image_embeddings(object_image : image):
"""
-----------------------------------------------------
convert image into 3d array and add additional dimension for model input
-----------------------------------------------------
return embeddings of the given image
"""
image_array = np.expand_dims(image.img_to_array(object_image), axis = 0)
image_embedding = vgg16.predict(image_array)
return image_embedding
#、余弦相似度计算
def get_similarity_score(first_image : str, second_image : str):
"""
-----------------------------------------------------
Takes image array and computes its embedding using VGG16 model.
-----------------------------------------------------
return embedding of the image
"""
first_image = load_image(first_image)
second_image = load_image(second_image)
first_image_vector = get_image_embeddings(first_image)
second_image_vector = get_image_embeddings(second_image)
similarity_score = cosine_similarity(first_image_vector, second_image_vector).reshape(1,)
return similarity_score
#、图像显示
def show_image(image_path):
image = mpimg.imread(image_path)
imgplot = plt.imshow(image)
plt.show()
#、两个图像的比较
# define the path of the images
sunflower = '/content/sunflower.jpeg'
helianthus = '/content/helianthus.jpeg'
tulip = '/content/Tulip.jpeg'
# use the show_image function to plot the images
show_image(sunflower), show_image(helianthus)
然后,我们将这些函数应用于一组图像,并使用各种技术将结果可视化。 总体而言,该项目展示了如何利用 VGG16 等深度学习模型来执行复杂的图像分析任务并从视觉数据中生成见解。 网友回复
视频大模型和最强文本大模型通过代码生成视频哪个性价比更高?
seedream5.5为啥无法将图白色背景修改成透明?
seedance2如何通过2张不同角度平视图来识别场景进行人物定位?
有没有免费的浏览器中离线运行的语音识别ai模型?
微信小程序个人版不交钱认证就不让你用二维码,报错"errcode":85411?
美丽国为啥要限制ai发展?
seedance2如何参考白模视频使用真实场景和人物生成新视频?
如何设定小孩看电视的时候每隔10分钟弹出一个题目,答对才能继续,答错继续下一题?
直播数字人根据公屏互动评论实时做出不用动作技术是什么?
未来ai文本大模型根据剧本直接生成像素风或三维白模或灰模粗糙场景动画html给视频大模型参考站位与运镜?


