如何使用python计算二值图像中的黑白像素

如何使用python计算二值图像中的黑白像素,python,Python,当我运行此代码时,出现以下错误:- from PIL import Image import PIL.ImageOps import cv2 import numpy as np from matplotlib import pyplot as plt # read image img = cv2.imread('bnw11.png') height, width = img.shape print "height and width : ",height, width size =

当我运行此代码时,出现以下错误:-

from PIL import Image
import PIL.ImageOps 
import cv2
import numpy as np 
from matplotlib import pyplot as plt

# read image

img = cv2.imread('bnw11.png')
height, width = img.shape
print "height and width : ",height, width

size = img.size
print "size of the image in number of pixels", size 

# plot the binary image

cv2.imshow('binary',img)
回溯(最近一次呼叫最后一次):
文件“C:/Python27/BnW.py”,第9行,在
高度、宽度=img.shape
ValueError:要解压缩的值太多

我的图像已经是二值图像了。我想计算几个二值图像中的黑白像素数。。。我是新手..欢迎您提供任何帮助..

错误是因为
img.shape
返回的元组大小大于或小于2,正如您在
height,width=img.shape
中所假设的那样。在图像作为numpy数组的上下文中,
.shape()
在RGB图像的情况下返回3个值,因此您可以将其更改为

Traceback (most recent call last):
File "C:/Python27/BnW.py", line 9, in <module>
height, width = img.shape
ValueError: too many values to unpack
但如果是灰度图像,则高度、宽度=img。形状就可以了

height, width, channels = img.shape