如何比较 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==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]]])
例如我有两张图片
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==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]]])