Skip to content Skip to sidebar Skip to footer

How To Check If All Items In List Of Rgb Colors Is In An Image Without A Loop?

Say I have a list of RGB values as follows: rgbL = [[20 45 40] [30 45 60] .... [70 50 100]] Then, I have an image say, img = cv.imread('location') Now, I want to change ALL RGB va

Solution 1:

convert your rgbL and img into numpy arrays. one way of doing it without loop:

sh = img.shape
img = img.reshape(-1, 3)
img[np.where(((rgbL[:,None,:]-img)==0).all(axis=2))[1]]=np.array([255,0,0])
img = img.reshape(sh)

which takes a difference of your image with every row of rgbL and checks for all zero difference in RGBs to replace using np.where.

sample img and output:

img:
[[ 20  45  40]
 [ 30  45  60]
 [  0   1   2]
 [ 70  50 100]
 [  4   5   6]]
rgbL:
[[ 20  45  40]
 [ 30  45  60]
 [ 70  50 100]]
Output:
[[255   0   0]
 [255   0   0]
 [  0   1   2]
 [255   0   0]
 [  4   5   6]]

UPDATE: Per OP's comment on converting string dict keys to numpy arrays:

rgbL = np.array([list(map(int,[s.strip() for s in key.strip('[').strip(']').strip(' ').split(' ') if s.strip()])) for key in rgb_dict.keys()])

Solution 2:

The algorithm mentioned above is O(length of rgbL * size of image)

We can bring it down to O(length of the rgbL + size of image)

set_rgbl = set(rgbL)
height = img.shape[0]
width = img.shape[1]
BLUE_COLOR = (255, 0, 0)

for h in range(0, height):
    for w in range(0, width):
        if list(img[h, w]) in set_rgbl:
            img[h, w] = BLUE_COLOR

What happens here is that we created a set of rgbL values. The insert in set is constant time operation. Same holds for lookup. Hence, when we are iterating over every pixel values in image for every pixel we spend O(1) time. This leads to improvement in our time complexity.

Hope that helps.

Post a Comment for "How To Check If All Items In List Of Rgb Colors Is In An Image Without A Loop?"