Monojit Sarkar
Monojit Sarkar

Reputation: 717

How to calculate histogram of an image?

How can I solve the below error?

   import cv2

   img= cv2.imread('/home/monojit/Desktop/crop.jpg')
   hsv= cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

   hist= cv2.calcHist([hsv],[0,1],None,[256],[0,256])
   print(hist)

   cv2.imshow('img',hsv)
   cv2.waitKey(0)
   cv2.destroyAllWindows()

But on execution the get the following error:

Traceback (most recent call last):
File "/home/monojit/Desktop/hisCalc.py", line 6, in <module>
hist= cv2.calcHist([hsv],[0,1],None,[256],[0,256])
error: OpenCV(3.4.1) /home/monojit/Desktop/OpenCV/modules/imgproc/src/histogram.cpp:1782: error: (-215) csz == 0 || csz == dims in function calcHist

How do I solve the error?

Upvotes: 2

Views: 799

Answers (1)

Aleksey Petrov
Aleksey Petrov

Reputation: 370

The problem is here:

hist= cv2.calcHist([hsv],[0,1],None,[256],[0,256])

The real answer to the problem depends on what you want.

Second parameter is a channel number. So if you want to have a 1d histogram of one channel (for example, Hue), you should change it to

hist= cv2.calcHist([hsv],[0],None,[256],[0,256])

Fourth and fifth parameters are numbers of bins and ranges for every channel. And if you want to have 2d histogram of the Hue and Saturation channels, you should change it to

hist = cv2.calcHist([hsv], [0, 1], None, [256, 256], [0, 256, 0, 256])

Upvotes: 3

Related Questions