Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why using cv2.calcHist always has an errer "returned NULL without setting an error"

I am using Opencv with python, and come across a question.
When I run the following code:

img = cv2.imread('test.jpg',0)
hist = cv2.calcHist([img],[0],None,256,[0,256])

An error occurs: SystemError: <built-in function calcHist> returned NULL without setting an error
I am confused and can not find the same error in networks, so what's wrong?
Thanks.

PS: I run the same code in both Windows and Ubuntu,and get the same error,so it may not the reason of system ?

like image 893
digger Avatar asked Mar 20 '19 02:03

digger


People also ask

What does the cv2 calcHist return?

The calcHist() function returns a 256*1 array in which each value is a pixel value and corresponds to the pixel values in the given image.

What is cv2 calcHist?

In this example, we calculate the histogram of the blue color channel of the input image “mountain. jpg” using cv2. calcHist() function. We pass the parameter channels = [0] to calculate the histogram of the blue channel. We also plot the histogram using Matplotlib.


2 Answers

The error message is confusing indeed, but the actual error is simple. Even though you're just using 1 channel, you still need to give a list of histogram sizes and ranges. You've done that for the range, but not for the size. This should work:

img = cv2.imread('test.jpg',0)
hist = cv2.calcHist([img],[0],None,[256],[0,256])

Wo-Ki anticipates your next problem, as it's unusual to make a histogram of just the blue channel, and you probably want a histogram of the intensity instead. In that case, use the intermediate conversion step as Wo-Ki suggested.

like image 198
user3622622 Avatar answered Sep 21 '22 03:09

user3622622


I had the same problem. Apparently the ranges [0, 256] have to be same type as img. Try

hist = cv2.calcHist([img.astype('uint8')],[0],None,[256],[0, 256]) 

instead. It should work fine.

like image 29
bortizj Avatar answered Sep 17 '22 03:09

bortizj