calcHist - returned NULL without setting an error

I am using Python 3.6.7, Open<cv, PyQt5 5.15.2

I have a .tif image of size (222, 230), im2 dtype = uint16, and I created a mask of size (222, 230), mask2 dtype = uint16.

Here is a snippet of my code below :-

im2 = cv2.imread(input_dir,  flags= (cv2.IMREAD_GRAYSCALE | cv2.IMREAD_ANYDEPTH))
mask2 = np.zeros(im.shape, dtype = np.uint16)
mask2 =, (165, 151), 75, (255,255,255), -1)
hist = cv2.calcHist(im2, [0], mask2, 256, [0,65536])

And I get the following error,

Traceback (most recent call last):
  File "", line 38, in <module>
    hist = cv2.calcHist(im2, [0], mask2, 256, [0,65536])
SystemError: <built-in function calcHist> returned NULL without setting an error

Can someone help me understand what is my mistake here?

Thanks in advance!

from docs :

mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as images[i]

(yours is 16bit)

also, it should be a list of images, like [im2]
and a list of ranges, like [256]

all in all, try:

mask2 = np.zeros(im.shape, dtype = np.uint8)
mask2 =, (165, 151), 75, (255), -1)
hist = cv2.calcHist([im2], [0], mask2, [256], [0,65536])

have another look at the tutorial, please.

that concerns me. it should have been able to give a better error.

if the issue persists, try this:

you may want to use OPENCV_PYTHON_DEBUG=1 environment variable.

(similar issue, not same: SystemError: returned NULL without setting an error · Issue #18821 · opencv/opencv · GitHub )

another issue with calcHist and useless error message: python - why using cv2.calcHist always has an errer "returned NULL without setting an error" - Stack Overflow

me too. here’s the generated wrapper code:

i think, it falls through both PyArg_ParseTupleAndKeywords calls
(bc missing array around im2 ??)

Dear Berak,

Yes, right, thanks for pointing it out!
Sorry there were few examples online with and without [] and i got confused.

I no longer receive this error!

1 Like