试图解决防止上传重复图像的问题。
我有两个JPG。看着它们,我可以看到它们实际上是相同的。但是由于某种原因,它们具有不同的文件大小(一个是从备份中提取的,另一个是另一个上传的),因此它们具有不同的 md5 校验和。
我怎样才能有效而自信地比较两个图像,就像人类能够看到它们明显相同一样?
示例: http ://static.peterbe.com/a.jpg 和 http://static.peterbe.com/b.jpg
更新
我写了这个脚本:
import math, operator
from PIL import Image
def compare(file1, file2):
image1 = Image.open(file1)
image2 = Image.open(file2)
h1 = image1.histogram()
h2 = image2.histogram()
rms = math.sqrt(reduce(operator.add,
map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
return rms
if __name__=='__main__':
import sys
file1, file2 = sys.argv[1:]
print compare(file1, file2)
然后我下载了两个外观相同的图像并运行了脚本。输出:
58.9830484122
谁能告诉我合适的截止值应该是多少?
更新二
a.jpg 和 b.jpg 的区别在于第二个是用 PIL 保存的:
b=Image.open('a.jpg')
b.save(open('b.jpg','wb'))
这显然应用了一些非常轻质量的修改。我现在解决了我的问题,将相同的 PIL 保存到正在上传的文件中,而不用做任何事情,它现在可以工作了!
原文由 Peter Bengtsson 发布,翻译遵循 CC BY-SA 4.0 许可协议
有一个 OSS 项目使用 WebDriver 截屏,然后对比图片看是否有问题( http://code.google.com/p/fighting-layout-bugs/ )。它通过将文件打开到流中然后比较每一位来实现。
您也许可以使用 PIL 做类似的事情。
编辑:
经过更多研究,我发现
在 http://snipplr.com/view/757/compare-two-pil-images-in-python/ 和 http://effbot.org/zone/pil-comparing-images.htm