查找相似图像算法在Python中无法正常工作

2024-05-28 23:36:42 发布

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

我从这个Git采用了一个类似的图像查找器,它似乎是一个接地的well explained solution,但它不能正常工作。虽然我尝试了许多不同的设置,但代码显示的所有图像与其他图像相似。它不是跳过一个

以下是完整的代码:

from PIL import Image
import numpy as np 
import imagehash
import cv2
import sys

path = 'D:/Images/'

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(path) if isfile(join(path, f)) and '.jpg' in f.lower()]

similarity = 80
hash_size  = 8

threshold  = 1 - similarity/100
diff_limit = int(threshold*(hash_size**2))

for image in onlyfiles:
    # image for comparison
    with Image.open(path + image) as img:
        hash1 = imagehash.average_hash(img, hash_size).hash 
        
    # compare with other images
    for image2 in onlyfiles:
        if image2 == image: continue # skip same image file 
        with Image.open(path + image) as img2:
            hash2 = imagehash.average_hash(img2, hash_size).hash 
        if np.count_nonzero(hash1 != hash2) <= diff_limit:
            print('similar images found!')

            # display images / for visual comparison only
            image1 = cv2.imread(path+image) 
            cv2.imshow('image1',image1)
            image2 = cv2.imread(path+image2)
            cv2.imshow('image2', image2)
            cv2.waitKey(0)
            cv2.destroyAllWindows() 
        else:
            print('not similar')

当寻找相同的图像(在不同的代码中)时,hash_size的值为10时效果更好(8太小了)。当我将此程序中的similarityhash_size更改为其他值时,不会发生任何事情,但程序会以类似的方式传递所有图像


Tags: path代码infrom图像imageimportfor

热门问题