chan5464
chan5464

Reputation: 11

how to count black and white pixels in binary image using 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 = img.size
print "size of the image in number of pixels", size 

# plot the binary image

cv2.imshow('binary',img)

when i run this code i get the following error:-

Traceback (most recent call last):
File "C:/Python27/BnW.py", line 9, in <module>
height, width = img.shape
ValueError: too many values to unpack

my image is already a binary one.I want to count no of black and white pixels in several binary images... i m newbie..am open to any help that you can give..

Upvotes: 1

Views: 1354

Answers (1)

ZdaR
ZdaR

Reputation: 22954

The error is because img.shape is returning a tuple of size greater or less than 2 as assumed by you in height, width = img.shape. In context of images as numpy array, the .shape() returns 3 values in case of RGB images, so you may change it to

height, width, channels = img.shape

but in case of GrayScale imgaes height, width = img.shape would work fine.

Upvotes: 1

Related Questions