MsX
MsX

Reputation: 21

Finding certain pixel value within image

I want to check for every pixel if it is red. Therefore I prepared a white image where I printed some red lines. The red lines are exactly of this colour: (0, 0, 255).

With the following code, no red is detected in the image. What is wrong?

import cv2
import numpy as np

img = cv2.imread(r"....\red.png")
x,y,z = img.shape
print(x,y,z)

for i in range(x):
    for j in range(y):
        r = np.where((img[i,j,0]==0 & img[i,j,1]==0 & img[i,j,2]==255))
        redarray = np.array(r)
        red = np.size(redarray)

print("r: ", r)
print("redarray: ", redarray)
print("red: ", red)

Upvotes: 0

Views: 1422

Answers (1)

busybear
busybear

Reputation: 10580

You don't need for-loops to accomplish this. One of the advantages of numpy!

np.where will do this with a little bit of work:

np.where((img == (0, 0, 255)).all(axis=2))

Following your example, you would need to create an if statement that would build a list of pixels if the pixel is red. redarray in your post will just reflect the current pixel each for loop iteration. You aren't building a list there. So something like this should work:

red_pixels = []
for i in range(x):
    for j in range(y):
        if np.array_equal(img[i, j], [0, 0, 255]):
            red_pixels.append((i, j))

Upvotes: 1

Related Questions