繁体   English   中英

如何比较两个图像在 Python 中的相似程度?

[英]How to compare how similar two images are in Python?

我正在尝试将我正在拍摄的图像与我已经存储在计算机上的图像进行比较,如果它们足够相似则返回 True。 这是一个与此类似的问题

我正在使用 OpenCV,所以使用它会很好。 我目前的工作是使用 OpenCV 首先打开图像,然后灰度图像,然后模糊它们,然后将它们写回文件。 然后我使用 PIL 中的 Image 和 imagehash 在删除文件之前比较图像的哈希值。 有没有更好的方法来做到这一点?

这是我当前的代码:

def compareImg(imgWarpColor):
    img = cv2.imread("data.jpg")
    img = cv2.resize(img, (660, 880))
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = cv2.GaussianBlur(img, (3, 3), 0)
    cv2.imwrite("datagray.jpg", img)

    grayImgWarped = cv2.cvtColor(imgWarpColor, cv2.COLOR_BGR2GRAY)
    blurImg = cv2.GaussianBlur(grayImgWarped, (3, 3), 0)
    cv2.imwrite("blurredImage.jpg", blurImg)

    hash0 = imagehash.average_hash(Image.open('blurredImage.jpg'))
    hash1 = imagehash.average_hash(Image.open('datagray.jpeg'))
    cutoff = 5

    hashDiff = hash0 - hash1
    print(hashDiff)
    if hashDiff < cutoff:
        print('These images are similar!')

    filepath = 'C:\Users\MY NAME\PycharmProjects\projectInQuestion'
    
    os.remove(filepath, 'blurredImage.jpg')
    os.remove(filepath, 'datagray.jpg')

我在 pyautogui 上取得了巨大的成功,但它就像实时图像匹配和自动化简单的 GUI 任务。 idk 如果有帮助,也许那里有一些类似的库依赖项>

这是一个快速编码的模型,绝不是一种有效的方法。 正如 frederick-douglas-pearce 所指出的,为了使用 OpenCV 和 PIL,您需要确保图像的格式相同。

OpenCV 将图像存储为 BGR,而 PIL 将图像存储为 RGB。 您可以通过执行以下操作将 OpenCV 图像转换为 PIL 图像:

pilImg = cv2.cvtColor(openCVImg, cv2.COLOR_BGR2RGB)

如果您有兴趣做类似于我的原始代码所做的事情,这将是一种更好的方法:

def compareImages(cv2Img):
    # Convert cv2Img from OpenCV format to PIL format
    pilImg = cv2.cvtColor(cv2Img, cv2.COLOR_BGR2RGB)
    
    # Get the average hashes of both images
    hash0 = imagehash.average_hash(pilImg)
    hash1 = imagehash.average_hash(Image.open('toBeCompared.jpeg'))
    cutoff = 5  # Can be changed according to what works best for your images
    
    hashDiff = hash0 - hash1  # Finds the distance between the hashes of images
    if hashDiff < cutoff:
        print('These images are similar!')

请注意,我最初是模糊和灰度图像; 这不是必需的,因为散列算法已经做了类似的事情。 此外,正如这篇文章的评论中所指出的,仅写入文件以删除它们是非常低效的,因此请尽可能远离这种情况。

如果average_hash()没有按预期工作,请考虑使用whash()phash()dhash()或这四者的某种组合,它们也可以在ImageHash库中找到。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM