将一幅图像与一组图像进行比较,以找到相似度最高的图像

2024-09-25 06:30:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用暹罗网络训练权重并进行预测。我查看源代码,将图像与图像进行比较,以预测相似性。
我想使用训练的权重将一张图片与一组图片进行比较,获得最高的相似度,并显示出来。我已经训练了权重,无法实现此预测。
源代码在这里,你能帮我看看我应该如何设计吗? Siamese network

 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

predict.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)
    

例如,我想对训练过的重量做的是预测这样的事情。 enter image description here使用此图片和下面的图片集进行预测。enter image description here
我们希望得到的是与第四张图片和视觉输出的最高相似度


Tags: imageselfnewinputsizedefnp图片