opencv imshow 函数显示 float64 格式错误_cv2_imshow float

在模拟高斯光斑的过程中,手动生成了下图所示的图像,使用cv2.imwrite()函数保存正常。

然而在使用cv2.imshow()函数显示时却出现错误

原因是使用高斯函数公式生成的图像,灰度值为 float64 格式,而cv2.imshow()不支持 float64,会自动转换,参考 opencv 文档:

imshow(winname, mat) -> None
. The function may scale the image, depending on its depth:
. - If the image is 8-bit unsigned, it is displayed as is.
. - If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256.
That is, the value range [0,255*256] is mapped to [0,255].
. - If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the
. value range [0,1] is mapped to [0,255].

所有像素都乘以 255,然后越界的在 255 处截断,因此显示大面积白色。
解决方法:
(1)直接截断为 np.uint8 格式

dist = cv2.convertScaleAbs(src)

效果如图

基本与原图一致,因为图像保存时也被自动截断。
(2)归一化到 [0, 255]

dist = cv2.normalize(src, None, 255,0, cv2.NORM_MINMAX, cv2.CV_8UC1)

效果如图

相当于经过了增强,失真比较严重

var code = "db6e4093-17fb-42e1-94e1-7f03c9fbefb2"
posted @ 2024-05-21 19:54  钢之炼丹术师  阅读(68)  评论(0)    收藏  举报