尝试解决防止重复图片上传的问题。
我有两个 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 保存到正在上传的文件,而不用做任何事情,它现在可以工作了!
最佳答案
有一个OSS项目使用WebDriver截屏然后对比图片看有没有问题(http://code.google.com/p/fighting-layout-bugs/))。它通过将文件打开到流中然后比较每一位来实现。
你也许可以用 PIL 做类似的事情.
编辑:
经过更多研究,我发现
h1 = Image.open("image1").histogram()
h2 = Image.open("image2").histogram()
rms = math.sqrt(reduce(operator.add,
map(lambda a,b: (a-b)**2, h1, h2))/len(h1))
关于 http://snipplr.com/view/757/compare-two-pil-images-in-python/和 http://effbot.org/zone/pil-comparing-images.htm
关于python - 比较两个图像的 python/linux 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1927660/