比较两个图像并在第二个图像上突出显示差异

问题描述 投票:0回答:3

下面是 python 中当前的工作代码,使用 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)
    h,w=diff.size
    new = diff.convert('RGB')
    new.paste(b, mask=diff)
    return new

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

https://drive.google.com/file/d/0BylgVQ7RN4ZhTUtUU1hmc1FUVlE/view?usp=sharing

image python-imaging-library
3个回答
11
投票

PIL确实有一些方便的图像处理方法, 但也有很多缺点 开始认真进行图像处理 -

大多数 Python 文献都会建议您切换 对像素数据使用 NumPy,这将给出 你完全控制- 其他成像库,例如 leptonica、gegl 和 vips 全部都有 Python 绑定和一系列不错的函数 用于图像合成/分割。

在这种情况下,问题是想象一个人会如何 在图像处理程序中获得所需的输出: 你可以用黑色(或其他颜色)的阴影来覆盖 原始图像,然后在其上粘贴第二张图像, 但使用阈值(即像素等于或 不同 - 所有中间值都应四舍五入 将差异的“不同”作为第二张图像的掩码。

我修改了你的函数来创建这样的组合 -

from PIL import Image, ImageChops, ImageDraw
point_table = ([0] + ([255] * 255))

def new_gray(size, color):
    img = Image.new('L',size)
    dr = ImageDraw.Draw(img)
    dr.rectangle((0,0) + size, color)
    return img

def black_or_b(a, b, opacity=0.85):
    diff = ImageChops.difference(a, b)
    diff = diff.convert('L')
    # Hack: there is no threshold in PILL,
    # so we add the difference with itself to do
    # a poor man's thresholding of the mask: 
    #(the values for equal pixels-  0 - don't add up)
    thresholded_diff = diff
    for repeat in range(3):
        thresholded_diff  = ImageChops.add(thresholded_diff, thresholded_diff)
    h,w = size = diff.size
    mask = new_gray(size, int(255 * (opacity)))
    shade = new_gray(size, 0)
    new = a.copy()
    new.paste(shade, mask=mask)
    # To have the original image show partially
    # on the final result, simply put "diff" instead of thresholded_diff bellow
    new.paste(b, mask=thresholded_diff)
    return new


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

2
投票

这是使用 libvips 的解决方案:

import sys
impoty pyvips

a = Vips.Image.new_from_file(sys.argv[1], access="sequential")
b = Vips.Image.new_from_file(sys.argv[2], access="sequential") 

# a != b makes an N-band image with 0/255 for false/true ... we have to OR the
# bands together to get a 1-band mask image which is true for pixels which
# differ in any band
mask = (a != b).bandbool("or")

# now pick pixels from a or b with the mask ... dim false pixels down 
diff = mask.ifthenelse(a, b * 0.2)

diff.write_to_file(sys.argv[3])

对于 PNG 图像,大部分 CPU 时间都花在 PNG 读写上,因此 vips 只比 PIL 解决方案快一点。

libvips 确实使用了更少的内存,特别是对于大图像。 libvips 是一个流媒体库:它可以同时加载、处理和保存结果,不需要在开始工作之前将整个图像加载到内存中。

对于 10,000 x 10,000 RGB tif,libvips 的速度大约是其两倍,并且需要大约 1/10 的内存。


1
投票

如果您不执着于使用 Python,有一些使用 ImageMagick 的非常简单的解决方案:

使用 ImageMagick“比较”图像

© www.soinside.com 2019 - 2024. All rights reserved.