繁体   English   中英

如何比较 python 中两个相同大小的图像,用黑色像素替换两个图像之间匹配的像素

[英]How to compare two identically sized images in python, replacing pixels that match between the two images with black pixels

例如我有两张图片

import numpy as np

img1 = np.array([[[1,1,1],[2,2,2]],[[3,3,3],[4,4,4]]])
img2 = np.array([[[1,1,1],[1,1,1]],[[3,3,3],[1,1,1]]])

我想比较两者,像素匹配的地方,不匹配的地方,使用 img1 中的像素,匹配的地方,用黑色像素替换像素

期望的结果:

[[[0,0,0],[2,2,2]],[[0,0,0],[4,4,4]]]

干得好:

img1[img1==img2] = 0

img1==img2上使用.all(-1)来检查所有通道上的相等性。 然后np.where与广播:

out = np.where((img1==img2).all(axis=-1)[...,None], (0,0,0), img1)

或者,由于您使用(0,0,0)进行屏蔽,因此您可以在img1!=img2上使用.any(axis=-1)来检测某个频道上的差异,然后进行广播和乘法:

out = (img1!=img2).any(axis=-1)[...,None] * img1

输出:

array([[[0, 0, 0],
        [2, 2, 2]],

       [[0, 0, 0],
        [4, 4, 4]]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM