使用PIL(Python成像库)按像素比较两个图像 [英] Comparing two images pixel-wise with PIL (Python Imaging Library)

查看:2028
本文介绍了使用PIL(Python成像库)按像素比较两个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个比较两个相同大小的PIL图像的功能。我们称它们为A和B.结果应该是一个相同大小的新图像。如果A和B中的像素相同,则应将其设置为固定颜色(例如黑色),否则应将其设置为与B相同的颜色。

I need a function which compares two PIL images of the same size. Let's call them A and B. The result is supposed to be a new image of the same size. If a pixels is the same in both A and B it's supposed to be set to a fixed color (e.g. black), otherwise it's supposed to be set to the same color as B.

是否有用于实现此功能的库而没有对所有像素进行昂贵的循环?

Is there a library for implementing this functionality without an expensive loop over all pixels?

推荐答案

不确定其他库,但你可以用PIL做这件事,比如......

Not sure about other libraries, but you can do this with PIL, with something like...

from PIL import Image, ImageChops

point_table = ([0] + ([255] * 255))

def black_or_b(a, b):
    diff = ImageChops.difference(a, b)
    diff = diff.convert('L')
    diff = diff.point(point_table)
    new = diff.convert('RGB')
    new.paste(b, mask=diff)
    return new

a = Image.open('a.png')
b = Image.open('b.png')
c = black_or_b(a, b)
c.save('c.png')

这篇关于使用PIL(Python成像库)按像素比较两个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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