将多个图像与一个图像进行比较

2024-09-28 23:43:41 发布

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

我试着把一张图片和一个满是图片的文件夹进行比较,并试图找到一张相等的图片,但我不知道如何把一张图片和一个满是图片的文件夹进行比较

我试着用fnmatch和os制作一个listOfFiles,但它只需要少数几个图像中的一个

#import 
import cv2
import numpy as np
import os, fnmatch

#Collects all images 
listOfFiles = os.listdir('./images')
pattern = "*.jpg"
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
            Allimages = ("images/" + entry)

#Define variables
upload = cv2.imread("images/img1.jpg")
duplicate = cv2.imread(Allimages)
#Checks if duplicate is duplicate 
if upload.shape == duplicate.shape:
    print("The images have same size and channels")
    difference = cv2.subtract(upload, duplicate)
    b, g, r = cv2.split(difference) 

    if cv2.countNonZero(b) == 0 and cv2.countNonZero (g) == 0 and cv2.countNonZero(r) == 0:
        print("images are the same")

else:
    print("images are different")

Tags: andimport文件夹ifos图片cv2upload
1条回答
网友
1楼 · 发布于 2024-09-28 23:43:41

必须在for循环内完成所有操作

也许你只能用

if (upload == duplicate).all():

代码:

import cv2
import os

directory = './images'
upload = cv2.imread("images/img1.jpg")

for entry in os.listdir(directory):

    if entry.lower().endswith( ('.jpg', '.jpeg', '.png', '.gif') ):

        fullname = os.path.join(directory, entry)
        print('fullname:', fullname)
        duplicate = cv2.imread(fullname)

        if upload.shape == duplicate.shape:
            print("The images have same size and channels")

            #difference = cv2.subtract(upload, duplicate)
            #b, g, r = cv2.split(difference) 
            #if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
            if (upload == duplicate).all():
                print("images are the same")

        else:
            print("images are different")

相关问题 更多 >