Skip to content
Advertisement

Remove [255,255,255] entries from list of image RGB values

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:

import cv2
import numpy as np

IM = cv2.imread('Test_image.png')
image = cv2.cvtColor(IM, cv2.COLOR_BGR2RGB)

# reshape the image to be a list of pixels
image_vec = np.array(image.reshape((image.shape[0] * image.shape[1], 3)))
image_clean = image_vec[image_vec != [255,255,255]]

print(image_clean)

enter image description here

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:

image_vec[~ np.all(image_vec == 255, axis=-1)]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement