opencv imshow 函式顯示 float64 格式錯誤_cv2_imshow float

钢之炼丹术师發表於2024-05-19

CSDN搬家失敗,手動匯出markdown後再匯入部落格園

在模擬高斯光斑的過程中,手動生成了下圖所示的影像,使用cv2.imwrite()函式儲存正常。

![[output/attachments/fa4dbbeff2a5a1f2f99acd241f220fc7_MD5.png]]

然而在使用cv2.imshow()函式顯示時卻出現錯誤

![[output/attachments/e80ba8f678e7ecde77c7a435afe81a08_MD5.png]]

原因是使用高斯函式公式生成的影像,灰度值為 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)

效果如圖

![[output/attachments/df78cfb4c85e42981cbd9797f6d4f71a_MD5.png]]

基本與原圖一致,因為影像儲存時也被自動截斷。
(2)歸一化到 [0, 255]

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

效果如圖

![[output/attachments/d3e6f80693d1209a7b4cc07a8c43aa19_MD5.png]]

相當於經過了增強,失真比較嚴重

相關文章