Error using cv2.equalizeHist
Solution 1
cv2.equalizeHist only works on grayscale ( 1 channel ) images. either:
im = cv2.imread("myimage.png", 0) # load as grayscale
or:
im = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # or convert
Solution 2
I got the same error, here is the solution:
Thanks to: zwep (Error using cv2.equalizeHist) and Reti43 (Conversion of image type int16 to uint8)
Error
The error is because the dtype of the array as zwep said.
But we can't just use img.astype(np.uint8)
or np.uint8(img)
; it will change the image. Here is the result.
- Raw Image(img):
plt.imshow(np.uint8(img),cmap=plt.cm.gray)
-
Solution
img1=np.uint8(cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)) plt.imshow(cv2.equalizeHist(img1),cmap=plt.cm.gray)
PS: Adaptive histogram equalization is better for MRI.
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
plt.imshow(clahe.apply(img1),cmap=plt.cm.gray)
Solution 3
If anyone else stumbled across this but is already using grayscale ($M \times N$) ndarrays... There can be another problem.
When you use cv2.imread()
it reads in the image as a numpy ndarray using dtype=np.uint8
. However, when I use any other method it can be stored as a dtype=np.uint16
which will trigger the following warning
OpenCV Error: Assertion failed (_src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3))) in cv::equalizeHist, file C:\projects\opencv-python\opencv\modules\imgproc\src\histogram.cpp, line 3913
Traceback (most recent call last):
File "<input>", line 1, in <module>
cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\histogram.cpp:3913: error: (-215) _src.type() == (((0) & ((1 << 3) - 1)) + (((1)-1) << 3)) in function cv::equalizeHist
Solution:
img_int8 = img.astype(np.uint8)
EDIT: might be doing something wrong though... because the output now gives strange results in some cases of transformation.
Shan
Updated on November 04, 2020Comments
-
Shan over 3 years
I am trying to equalize the histogram of a gray level image using the following code:
import cv2 im = cv2.imread("myimage.png") eq = cv2.equalizeHist(im)
The following exception is raised:
error: (-215) CV_ARE_SIZES_EQ(src, dst) && CV_ARE_TYPES_EQ(src, dst) && CV_MAT_TYPE(src->type) == CV_8UC1 in function cvEqualizeHist
The version of opencv is
2.4.2
Any guesses?
-
Cris Luengo about 6 yearsMaybe you need to scale your data so it fits in 8 bits?