I reshaped an image (included below) as a list of pixels, and now I want to remove the black ones (with value [255,255,255]
). What is an efficient way to do it?
I tried using IM[IM != [255,255,255]]
and I got a list of values, instead of a list of value triplets. Here is the code I’m using:
JavaScript
x
12
12
1
import cv2
2
import numpy as np
3
4
IM = cv2.imread('Test_image.png')
5
image = cv2.cvtColor(IM, cv2.COLOR_BGR2RGB)
6
7
# reshape the image to be a list of pixels
8
image_vec = np.array(image.reshape((image.shape[0] * image.shape[1], 3)))
9
image_clean = image_vec[image_vec != [255,255,255]]
10
11
print(image_clean)
12
Advertisement
Answer
The issue is that numpy automatically does array-boradcasting, so using IM != [255,255,255]
will compare each element to [255,255,255]
and return a boolean array with the same shape as the one with the image data. Using this as a mask will return the values as 1D array.
An easy way to fix this is to use np.all:
JavaScript
1
2
1
image_vec[~ np.all(image_vec == 255, axis=-1)]
2