gpt4 book ai didi

python - 如何正确使用 `cv2.imshow` 作为 `cv2.distanceTransform` 返回的浮点图像?

转载 作者:太空狗 更新时间:2023-10-30 01:52:59 24 4
gpt4 key购买 nike

cv2.imshow 发生了一些奇怪的事情。我正在编写一段代码,想知道为什么我的一个操作不起作用(通过观察 cv2.imshow 诊断)。恼怒的是,我最终将完全相同的图像写入了一个看起来不错的文件。为什么 cv2.imshow 显示二值图像(下图第一张),而 cv2.imwrite 按预期写入灰度图像(第二张图)?我以前从未遇到过显示灰度图像的问题!

cv2.imshow('Latest', image)
cv2.waitKey(0)
cv2.destroyAllWindows()

distTransform = cv2.distanceTransform(src=image,distanceType=cv2.DIST_L2,maskSize=5)
cv2.imwrite('distanceTransform.png', distTransform)

cv2.imshow('Latest', distTransform)
cv2.waitKey(0)
cv2.destroyAllWindows()

这是 cv2.imshow 显示的图像: distanceTransform.png as displayed by cv2.imshow (also the same as the input image)

这是由 imwrite 保存的图像: distanceTransform.png as written by imwrite

最佳答案

在使用cv2.imshow时,你应该知道:

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].

函数 distaceTransform 返回类型 float。所以直接显示dist时,先乘以255,再映射到[0,255]。所以结果就像二进制图像一样。 (0*255=>0, 1*255=>255, ...*255=>255)

正确显示:

(1) 您可以将 float dist 裁剪为 [0,255] 并通过 cv2.convertScaleAbs 将数据类型更改为 np.uint8

dist1 = cv2.convertScaleAbs(dist)

(2) 您还可以将 float dist 规范化为 [0,255] 并通过 cv2.normalize 更改数据类型

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

这是 Pandas 的例子:

enter image description here

结果:

enter image description here


完整代码:

#!/ust/bin/python3
# 2018.01.19 10:24:58 CST
img = cv2.imread("panda.png", 0)
dist = cv2.distanceTransform(src=img,distanceType=cv2.DIST_L2,maskSize=5)
dist1 = cv2.convertScaleAbs(dist)
dist2 = cv2.normalize(dist, None, 255,0, cv2.NORM_MINMAX, cv2.CV_8UC1)

cv2.imshow("dist", dist)
cv2.imshow("dist1", dist1)
cv2.imshow("dist2", dist2)
cv2.waitKey()

关于python - 如何正确使用 `cv2.imshow` 作为 `cv2.distanceTransform` 返回的浮点图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48331211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com