0
votes

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)
3
img has three dimensions, so img[i, j] is not a single value, but a vector. If the third dimension is 1, you can just do img[i, j, 0] instead. However, in that case, you can just do score = 2 * np.count_nonzero(img) - img.size.jdehesa
First of all print(score) won't work, also can you please show which library (at least, best will be how you define) you use to create the imageU12-Forward
The indentation of the print was wrong, I fixed it. To create the image I used openCV. I will update the question.Frederik Vanclooster
Variable and function name are same.. Not a good idea!Austin
there are opencv api to query the image format, the number of channels, the depth ecc. Please do that and, after, update your question, the following answers have no sense if you do not specify the details of the imageLeos313

3 Answers

1
votes

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().

0
votes

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

0
votes

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