对比图像文件 [英] Comparing Image Files

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

问题描述

我想创建比较两个图像的程序。它必须在2个文件夹,每个完整的图片,一个文件夹中的每个画面都有在其它文件夹一对(文件名相同)例如:文件夹1有3个图片:[a.png,b.png,c.png]和文件夹2有3个图片:[a.png,b.png,c.png。我想借文件夹1 / A和比较它FOLDER2 /年。我不知道从哪里开始。

I would like to create a program that compares two images. It must take in 2 folders, each full of pictures and each picture in one folder has a pair in the other folder (with the same filename) ex: folder1 has 3 pictures: [a.png, b.png, c.png], and folder2 has 3 pictures: [a.png, b.png, c.png]. I would like to take folder1/a and compare it to folder2/a. I do not know where to start.

推荐答案

您提到图片而不是文件等等我假设你不想要比较原始数据,但图像的像素,你可能还需要对图像之间的差别阈值

You mentioned images instead of file so I assume you don't want to compare raw data but the image pixels and you may also want to have threshold for difference between images

方法是怎样的做到这一点是比较使用PIL两个图像。 PIL有一个直方图功能,你可以用它来获取两个图像的直方图,然后得到一个RMS(均方根),例如

Easiet way to do that is compare two images using PIL. PIL has a histogram function, you can use that to get histogram for both images and then getting a RMS(root mean square) e.g.

import ImageChops
import math, operator

def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add,
        map(lambda h, i: h*(i**2), h, range(256))
    ) / (float(im1.size[0]) * im1.size[1]))

http://effbot.org/zone/pil-comparing-images复制。 HTM

一旦你拥有了它返回一个rmsdiff功能,可以使用在其他功能,迭代直通所有文件例如

once you have a function which returns rmsdiff, you can use that in another function which iterates thru all files e.g.

def diff_folder(folder1, folder2):
    for path1 in glob.glob(folder1+"/*.png"):
        filename = os.path.basename(path1)
        path2 = os.path.join(folder2, filename)
        if not os.path.exists(path2):
            continue
        im1 = Image.open(path1)
        im2 = Image.open(path2)
        diff = rmsdiff(im1, im2)
        if diff > threshold:
           print "different"

这篇关于对比图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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