比较python / linux方式的两个图像 [英] Compare two images the python/linux way

查看:131
本文介绍了比较python / linux方式的两个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试解决防止重复图像上传的问题。

Trying to solve a problem of preventing duplicate images to be uploaded.

我有两个JPG。看着它们,我可以看到它们实际上是相同的。但由于某种原因,它们具有不同的文件大小(一个是从备份中提取的,另一个是另一个上载),因此它们具有不同的md5校验和。

I have two JPGs. Looking at them I can see that they are in fact identical. But for some reason they have different file size (one is pulled from a backup, the other is another upload) and so they have a different md5 checksum.

我怎样才能有效和自信地比较两个图像,就像人类能够看到它们明显完全一样?

How can I efficiently and confidently compare two images in the same sense as a human would be able to see that they are clearly identical?

示例: 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)

然后我下载了两个视觉上相同的图像并运行了脚本。输出:

Then I downloaded the two visually identical images and ran the script. Output:

58.9830484122

有人可以告诉我什么是合适的截止值吗?

Can anybody tell me what a suitable cutoff should be?

更新II

a.jpg和b.jpg之间的区别在于第二个用PIL保存:

The difference between a.jpg and b.jpg is that the second one has been saved with PIL:

b=Image.open('a.jpg')
b.save(open('b.jpg','wb'))

这显然适用于一些非常轻质的修改。我现在已经解决了我的问题,将相同的PIL保存应用到正在上传的文件而不用它做任何事情它现在可以工作了!

This apparently applies some very very light quality modifications. I've now solved my problem by applying the same PIL save to the file being uploaded without doing anything with it and it now works!

推荐答案

有一个OSS项目使用WebDriver拍摄屏幕截图,然后比较图像以查看是否存在任何问题( http://code.google.com/p/fighting-layout-bugs/) )。它通过将文件打开成流然后比较每一位来实现。

There is a OSS project that uses WebDriver to take screen shots and then compares the images to see if there are any issues (http://code.google.com/p/fighting-layout-bugs/)). It does it by openning the file into a stream and then comparing every bit.

您可以使用 PIL执行类似的操作

编辑:

经过更多研究后我找到了

After more research I found

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 / linux方式的两个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆