Reputation: 329
I have two images, img1
and img2
. I'm trying to find everywhere in img1
that the color [0,204,204]
occurs and replace it with whatever is in img2
in the same place. I can use np.where()
to find the places where that color occurs and replace it with a different color directly:
img1[np.where((img1==[0,204,204]).all(axis=2))] = [255,255,0]
I'm unsure how to grab the indices of these cells as the shape of the images are 5070000 with 3 dimensions, so, I can't display the array's effectively. Looking over the numpy documentation, I think I can do something like:
img2[img1[img1==[0,204,204]]]
to get the indices of img1
where that color occurs and then call the same array position from img2
, but, I can't seem to get this syntax correct. Help?
Upvotes: 0
Views: 176
Reputation: 51335
If I understand correctly, you can use the following:
img1[np.where((img1==[0,204,204]).all(axis=2))] = img2[np.where((img1==[0,204,204]).all(axis=2))]
This works because the syntax you had originally (np.where((img1==[0,204,204]).all(axis=2))
) already returns the indices you are looking for
Example (on a small array):
img1 = np.array([[[0,204,204],[0,0,0],[1,2,3]]])
array([[[ 0, 204, 204],
[ 0, 0, 0],
[ 1, 2, 3]]])
img2 = np.array([[[0,1,2],[1,1,1],[2,7,3]]])
array([[[0, 1, 2],
[1, 1, 1],
[2, 7, 3]]])
img1[np.where((img1==[0,204,204]).all(axis=2))] = img2[np.where((img1==[0,204,204]).all(axis=2))]
>>> img1
array([[[0, 1, 2],
[0, 0, 0],
[1, 2, 3]]])
Upvotes: 1