我该如何比较两张图片?我发现了Python的PIL库,但我并不真正理解它是如何工作的。
我该如何比较两张图片?我发现了Python的PIL库,但我并不真正理解它是如何工作的。
要检查两个 jpg 文件是否完全相同,可以使用 pillow 库:
from PIL import Image
from PIL import ImageChops
image_one = Image.open(path_one)
image_two = Image.open(path_two)
diff = ImageChops.difference(image_one, image_two)
if diff.getbbox():
print("images are different")
else:
print("images are the same")
AssertionError: comparison of imgs failed: diff.getbbox()=None
,但我几乎确定它应该可以工作。为什么会这样呢? - Charlie Parkerimage_one = Image.open(path_one).convert('RGB')
image_two = Image.open(path_two).convert('RGB')
compare -metric AE $file1 $file2 /dev/null
。 - mara004AssertionError: comparison of imgs failed: diff.getbbox()=None
,但我几乎确定它应该可以工作。为什么会这样呢? - Charlie Parker看起来 Viktor 的实现在图像大小不同时可能会失败。
这个版本还比较 alpha 值。视觉上相同的像素被认为是相同的,例如 (0, 0, 0, 0) 和 (0, 255, 0, 0)。
from PIL import ImageChops
def are_images_equal(img1, img2):
equal_size = img1.height == img2.height and img1.width == img2.width
if img1.mode == img2.mode == "RGBA":
img1_alphas = [pixel[3] for pixel in img1.getdata()]
img2_alphas = [pixel[3] for pixel in img2.getdata()]
equal_alphas = img1_alphas == img2_alphas
else:
equal_alphas = True
equal_content = not ImageChops.difference(
img1.convert("RGB"), img2.convert("RGB")
).getbbox()
return equal_size and equal_alphas and equal_content
AssertionError: comparison of imgs failed: diff.getbbox()=None
,但我几乎确定它应该可以工作。为什么会这样呢? - Charlie Parker对于我来说确实有效,您只需要设置接受的不同像素的数量即可,在我的情况下是100,因为图像差异是完全黑色的图像,但仍然有25个不同的像素。我测试了其他完全不同的图像,它们有成千上万个不同的像素。
from PIL import ImageChops
if len(set(ImageChops.difference(img1, img2).getdata())) > 100:
print("Both images are diffent!")
您可以结合使用ImageChops.difference
和getbbox
:
from PIL import Image
from PIL import ImageChops
def are_equal(image_a: Image, image_b: Image) -> bool:
diff = ImageChops.difference(image_a, image_b)
channels = diff.split()
for channel in channels:
if channel.getbbox() is not None:
return False
return True
from pathlib import Path
from PIL import Image
import numpy as np
import PySimpleGUI as sg
def same(path1, path2):
try:
im1, im2 = Image.open(path1), Image.open(path2)
except Exception as e:
return e
ar1, ar2 = np.asarray(im1), np.asarray(im2)
im1.close(), im2.close()
return "Same Images" if np.array_equal(ar1, ar2) else "Different Images"
layout = [
[sg.Text("Image File 1"), sg.Input(key='File 1'), sg.FileBrowse()],
[sg.Text("Image File 2"), sg.Input(key='File 2'), sg.FileBrowse()],
[sg.Push(), sg.Button("Check"), sg.Push()],
[sg.Text("(Result)", size=0, justification='center', expand_x=True, key='Result')],
]
window = sg.Window('Comparison for two Image files', layout)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event == 'Check':
window['Result'].update(same(values["File 1"], values["File 2"]))
window.close()