简体   繁体   English

遍历所有像素以检查哪些像素为白色,哪些像素为黑色

[英]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. 它与img[i, j]语句有关。 How can there be multiple pixels in that aray? 该阵列中如何有多个像素? Am I not specifically calling one pixel by using img[i,j] ? 我不是通过使用img[i,j]专门调用一个像素吗? Does someone know how I could fix this, or if there is another working method for accessing 1 specific pixel? 有人知道我该如何解决这个问题,或者是否有另一种可以访问1个特定像素的工作方法?

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. 使用openCV库读取图像。 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]给出了具有RGB值的数组

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

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

And these arrays are not associated to True or False . 并且这些数组不与TrueFalse关联。 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() . 您的条件需要all()

It means that your array has got 3 dimension. 这意味着您的数组具有3维。 You can print img[i,j] to see how it looks like. 您可以打印img[i,j]以查看其外观。 The value you want is probably often at the same position so calling img[i,j,0] or img[i,j,1] should work 您想要的值可能经常位于同一位置,因此调用img[i,j,0]img[i,j,1]应该可以

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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