简体   繁体   中英

Iterate over all pixels to check which pixels are white and which are black

I'm trying to iterate over an image with only black and white pixels. For every black pixel I want to decrease a score, while for each white pixel I would like to increase a score. However upon testing the following code I get this error:

ValueError: The truth value of an array with more than one element is ambiguous.

It has something to do with the img[i, j] statement. How can there be multiple pixels in that aray? Am I not specifically calling one pixel by using img[i,j] ? Does someone know how I could fix this, or if there is another working method for accessing 1 specific pixel?

def score(img):
    score = 0

    height, width, _ = img.shape
    for i in range(height):
        for j in range(width):
            if img[i, j] == [255,255,255]:
                score = score + 1
            else:
                score = score - 1
    print(score)

The image was read using the openCV library. The original image is then filtered for a specific color, with which a mask is created. This mask only has black and white pixels, as mentioned before.

img = cv2.imread("images/test.jpg")
mask = cv2.inRange(img, lower_bound, upper_bound)

This happens because img[i, j] gives an array with the RGB values

img[i, j] = [0, 0, 0] # for black

img[i, j] = [255, 255, 255] # for white

And these arrays are not associated to True or False . You need to change your condition.

>>> img[0,0] == [0,0,0]
array([ True,  True,  True])
>>> all(img[0,0] == [0,0,0])
True

Your condition needs an all() .

It means that your array has got 3 dimension. You can print img[i,j] to see how it looks like. The value you want is probably often at the same position so calling img[i,j,0] or img[i,j,1] should work

Here you go =^..^=

from PIL import Image

# load image
img = Image.open('BlackWhite.gif').convert('RGB')
pixel = img.load()

# calculate the score
score = 0
w=img.size[0]
h=img.size[1]
for i in range(w):
  for j in range(h):
      if pixel[i, j] == (255, 255, 255):
          score += 1
      elif pixel[i, j] == (0, 0, 0):
          score -= 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM