使用PIL(Python成像库)逐个像素地比较两个图像

Maa*_*ten 11 python image-processing python-imaging-library

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

是否有用于实现此功能的库,而不需要在所有像素上使用昂贵的循环?

Aya*_*Aya 17

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

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')
Run Code Online (Sandbox Code Playgroud)

  • 这是做什么的? (2认同)