Home > database >  How to compare two identically sized images in python, replacing pixels that match between the two i
How to compare two identically sized images in python, replacing pixels that match between the two i

Time:11-01

I have two images for example

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]]])

I'd like to compare the two and, where the pixels are matching, and where they don't match, use the pixels from img1, and where they do match, replace the pixels with black pixels

desired result:

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

CodePudding user response:

Here you go:

img1[img1==img2] = 0

CodePudding user response:

Use .all(-1) on img1==img2 to check for equality on all channels. Then np.where with broadcasting:

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

Or, since you are masking with (0,0,0), you can use .any(axis=-1) on img1!=img2 to detect difference on some channel, then broadcast and multiply:

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

Output:

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

       [[0, 0, 0],
        [4, 4, 4]]])
  • Related