python - 将图像与一组图像进行比较,以找到相似度最高的图像
问题描述
我使用siamese网络训练权重并进行预测。我查看源代码将图像与图像进行比较以预测相似度。
我想用我训练的权重来比较一张图片和一组图片,得到最高的相似度,并展示出来。我训练了权重,这个预测的实现是做不到的。
源代码在这里,你能帮我看看我应该如何设计吗?
连体网
def letterbox_image(self, image, size):
image = image.convert("RGB")
iw, ih = image.size
w, h = size
scale = min(w/iw, h/ih)
nw = int(iw*scale)
nh = int(ih*scale)
image = image.resize((nw,nh), Image.BICUBIC)
new_image = Image.new('RGB', size, (128,128,128))
new_image.paste(image, ((w-nw)//2, (h-nh)//2))
if self.input_shape[-1]==1:
new_image = new_image.convert("L")
return new_image
@tf.function
def get_pred(self, photo):
preds = self.model(photo, training=False)
return preds
#---------------------------------------------------#
# Detection of image
#---------------------------------------------------#
def detect_image(self, image_1, image_2):
image_1 = self.letterbox_image(image_1,[self.input_shape[1],self.input_shape[0]])
image_2 = self.letterbox_image(image_2,[self.input_shape[1],self.input_shape[0]])
image_1 = np.asarray(image_1).astype(np.float64)/255
image_2 = np.asarray(image_2).astype(np.float64)/255
if self.input_shape[-1]==1:
image_1 = np.expand_dims(image_1,-1)
image_2 = np.expand_dims(image_2,-1)
photo1 = np.expand_dims(image_1,0)
photo2 = np.expand_dims(image_2,0)
output = np.array(self.get_pred([photo1,photo2])[0])
plt.subplot(1, 2, 1)
plt.imshow(np.array(image_1))
plt.subplot(1, 2, 2)
plt.imshow(np.array(image_2))
plt.text(-12, -12, 'Similarity:%.3f' % output, ha='center', va= 'bottom',fontsize=11)
plt.show()
return output
预测.py
if __name__ == "__main__":
model = Siamese()
while True:
image_1 = input('Input image_1 filename:')
try:
image_1 = Image.open(image_1)
except:
print('Image_1 Open Error! Try again!')
continue
image_2 = input('Input image_2 filename:')
try:
image_2 = Image.open(image_2)
except:
print('Image_2 Open Error! Try again!')
continue
probability = model.detect_image(image_1,image_2)
print(probability)
例如,我想要对训练过的权重做的是预测这样的事情。
使用这张图片和下面的一组图片进行预测。
我们希望得到的是与第四张图片和视觉输出的最高相似度。
解决方案
推荐阅读
- python - Python GUI 中布尔参数的可视化
- google-apps-script - 如何使用 Google Scripts Sheet 将电子表格表格放入电子邮件中
- xcode - containerPortal 为 NULL xcode 断言失败
- angular - 如何在 Angular 中使用 ng-content 替换内容
- laravel - Facebook\WebDriver\Exception\WebDriverCurlException: 带有参数的 http POST 引发 Curl 错误:{"type":"browser"}
- json - 如果 JSON 输出中的数组内有 anr 数组,如何迭代 json 数据
- asp.net-core - .Net Core 无法在 cookie 过期后发布到注销页面
- c++ - 这个 C++ 代码发生了什么?为什么sua = 20?
- mysql - 三个表的join和group_concat
- javascript - 单选项卡多内容引导程序 4