josuaschenk
josuaschenk

Reputation: 95

Numpy Image Array Replace specific color with 1, other colors with 0

I have to Encode an Image for Semantic Segmentation. The Input Image is of shape (128, 256, 3) with 128 x 256 RGB Values. I want an Output Shape of (128, 256) where every 1 represent, that the pixel matched the given Color and 0 represents, that another RGB Value was present.

[[20, 20, 20], [30, 30, 30], [40, 40, 40]] with the Filter [20,20,20] should result in [1, 0, 0]

Any Help would be greatly appreciated.

Optimally This Method should be feasible to apply to an array of shape (16, 128, 256, 3) with 16 pictures in it, applying the filter to every picture.

Upvotes: 1

Views: 1202

Answers (1)

Udi
Udi

Reputation: 172

Using np.where for one image:

filter_pixel = np.array([20, 20, 20])
image = np.array([[[20, 20, 20], [30, 30, 30], [40, 40, 40]],
                  [[20, 10, 20], [20, 20, 20], [40, 40, 40]]])

new_image = np.where(np.all(image == filter_pixel, axis=2), 1,0)
print(new_image)

Output:

[[1 0 0]
 [0 1 0]]

edit, for a number of images:

filter_pixels = np.array([[20, 20, 20], [30, 30, 30]])
filter_pixels = filter_pixels[:, np.newaxis, np.newaxis, :]
images = np.array([[[[20, 20, 20], [30, 30, 30], [40, 40, 40]],
                    [[20, 10, 20], [20, 20, 20], [40, 40, 40]]],
                  [[[20, 20, 20], [30, 30, 30], [40, 40, 40]],
                   [[20, 10, 30], [20, 20, 20], [30, 30, 30]]]])

new_images = np.where(np.all(images == filter_pixels, axis=3), 1, 0)

print(new_images)

Output:

[[[1 0 0]
  [0 1 0]]

 [[0 1 0]
  [0 0 1]]]

Upvotes: 1

Related Questions