我正在寻找一种算法来比较两个图像(我使用 python)。
我找到了 PIL 库、numpy/scipy 和 opencv。我知道如何进行灰度转换、二进制转换、制作直方图……没关系,但我不知道我必须对这两个图像做什么才能说“是的,它们相似//它们可能相似// 他们不匹配”。
你知道正确的方法吗?
如果你想检查它们是否二进制相等,你可以计算它们的校验和并进行比较。如果您想检查它们是否以其他方式相似,它将更加复杂,并且绝对不适合在 Stack Overflow 上发布的简单答案。这仅取决于您如何定义相似性,但无论如何这需要良好的编程技能和编写大量代码。
我放在一起的脚本,用于视觉检查图像的变化。结果是一个白色的图像,除了不同的像素。像素按比例变暗,差异越大;并且它们被“着色”以显示颜色变化,例如,如果旧图像更红,则差异图像将显示青色区域;如果新图像被更多读取,则差异图像将显示红色区域。
唯一的缺陷是速度慢,但我确信可以使用 numpy 或简单地使用处理像素组的理解来改进它。
#!/usr/bin/env python
TINT = 1 # exxagerate differences in tone
MINUTE = 5 # less than "x" points of difference
INCREASE_MINUTE = 2 # boost of minute differences
import sys
from PIL import Image
img1 = Image.open(sys.argv[1])
img2 = Image.open(sys.argv[2])
i1 = img1.load()
i2 = img2.load()
if img1.size != img2.size:
print "Images %s and %s have different sizes, cannot compare" \
% (sys.argv[1], sys.argv[2])
sys.exit(1)
imgmap = Image.new( 'RGB', img1.size, "white")
imap = imgmap.load()
row_averages = []
for y in range(img1.size[1]):
for x in range(img1.size[0]):
p1 = i1[x, y]
p2 = i2[x, y]
diffpixel = [255, 255, 255]
# color differences
diffs = [p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]]
absdiff = reduce(lambda a, b: abs(a) + abs(b), diffs)
diffsmag = [a * TINT for a in diffs]
diffplus = [max(0, a) for a in diffs]
totplus = reduce(lambda a, b: a + b, diffplus)
diffminus = [min(0, a) for a in diffs]
# apply negative differences (e.g. less red -> take red)
diffpixel = [ a + b for a, b in zip(diffpixel, diffminus)]
# subtract positive differences (e.g. more red -> take from non-red channels)
diffpixel = [ a - totplus for a in diffpixel ]
# ... put back what we took from red
diffpixel = [ a + b for a, b in zip(diffpixel, diffplus)]
if absdiff > 0 and absdiff < MINUTE:
# Increase contrast of minute differences
diffpixel = [a - INCREASE_MINUTE for a in diffpixel]
diffpixel = [max(0, a) for a in diffpixel]
imap[x, y] = tuple(diffpixel)
imgmap.save(sys.argv[3])