python 全局直方图均衡化equalizeHist报错

报错信息:
error: OpenCV(4.0.1) ../modules/imgproc/src/histogram.cpp:3345: error: (-215:Assertion failed) _src.type() == CV_8UC1 in function 'equalizeHist'

  原因:

cv2.equalizeHist(img)

中img需要为uint8类型,而,查看当前img 类型为

 

查看源代码:

img = Image.open(r'/data/UserData/ASA_airglow_image/plasma_bubble_20130929-30/20130929203232_gpi408_3_6300_180000_B1_G3.png.raw.png')
img_gray = ori.convert("L")

用Image读取图像时,即使转为灰度图,还是float64,需要转换为uint8。

尝试了两种方法:

方法1:每个像素进行变换

# 将numpy.float64转换为uint8
for i in range(img_gray.shape[0]):
    for j in range(img_gray.shape[1]):
        img_gray[i][j] = np.uint8(img_gray[i][j])

方法2:所有像素进行变换

img_gray = img_gray.astype(np.uint8)

 两种方法均能转换成功。

再次查看

print(type(img_gray[2][2]),img_gray.shape)

 

注意:类型转换前,为了保持原始图像中各点像素值大小比例不变,应该先将数据映射到0-255,再进行 类型转换。否则,float64中大于255的像素点会在转换类型时被截断,像素点数值大小比例发生变化。

你可能感兴趣的:(Python)