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

标签 python opencv image-processing

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/

相关文章:

C++ - 将 unsigned char* 复制到新的 unsigned char* 数组

python - 如何在 python 对象中有效地使用 Session 来将 tensorflow 作为实现细节?

python - 如何在QGraphicsView中获取鼠标释放坐标

python - 导入错误 : dlopen(/Users/Desktop/myapp/target/myapp_mac/cv2/cv2. cpython-36m-darwin.so, 2)

java - 将 WMF 转换为 PNG/BMP/JPG

ios - 如何在 imageview ios 中获取自定义图像的像素颜色值?

python - 如何根据opencv python中的掩码删除图像组件?

python - 如何将多个用户添加到 Django 中的单个 auth_group

python - 比较两个以上的列表

java - 将MatOfInt转换为MatofPoint