python - 函数 'distanceTransform'中的错误-使用OpenCV(3.4.9)的Python

标签 python opencv

我正在尝试使用距离变换来绘制轮廓,但出现错误:

out = cv2.distanceTransform(mask, distanceType=cv2.DIST_L2, maskSize=5)
cv2.error: OpenCV(3.4.9) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/distransform.cpp:724: error: (-215:Assertion failed) src.type() == CV_8UC1 in function 'distanceTransform'

这是我的代码:
import cv2
import imutils

pathToThePhoto = 'labrador.jpg'

img = cv2.imread(pathToThePhoto)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 100 , 255, cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

c = max(cnts, key=cv2.contourArea)
mask = cv2.drawContours(gray, [c], -1, (0, 255, 255), 2) #Edit: Changed from img to gray

out = cv2.distanceTransform(mask, distanceType=cv2.DIST_L2, maskSize=5)

cv2.imshow("distance-transform", out)
cv2.waitKey(0)
cv2.destroyAllWindows()

labrador.jpg:

enter image description here

编辑后的结果:

enter image description here

看起来不正确,还是可以?

最佳答案

问题是cv2.distanceTransform的输出类型为np.float32
在显示out之前,您需要标准化 out到[0,1]范围。

参见OpenCV documentation:

Normalize the distance image for range = {0.0, 1.0}
so we can visualize and threshold it
cv.normalize(dist, dist, 0, 1.0, cv.NORM_MINMAX)
cv.imshow('Distance Transform Image', dist)



这是代码:
import cv2
import imutils

pathToThePhoto = 'labrador.jpg'

img = cv2.imread(pathToThePhoto)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 100 , 255, cv2.THRESH_BINARY)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)

c = max(cnts, key=cv2.contourArea)
mask = cv2.drawContours(gray, [c], -1, 255, 2) #Edit: Changed from img to gray

out = cv2.distanceTransform(mask, distanceType=cv2.DIST_L2, maskSize=5)

# Normalize the distance image for range = {0.0, 1.0}
# so we can visualize and threshold it
out = cv2.normalize(out, out, 0, 1.0, cv2.NORM_MINMAX)

cv2.imshow("distance-transform", out)
cv2.waitKey(0)
cv2.destroyAllWindows()
out:
enter image description here

我不确定这是否是您的预期结果。
您正在与小狗一起在图像上应用距离变换。
mask:
enter image description here

关于python - 函数 'distanceTransform'中的错误-使用OpenCV(3.4.9)的Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204462/

相关文章:

Python httplib2 处理异常

python - Optional[Type[Foo]] 在 Python 3.5.2 中引发 TypeError

python - 在 list.extend 中删除这个不需要的副本

python - 如何从 Pandas 的数据帧标题中有效提取日期年份?

python - cv2.rectangle()不做任何事情

linux - 如何使用Libde265和Linux实现实时视频编码

Android Marshmallow - 从另一个库模块调用库模块( native 库)崩溃

python - 如何创建基于 file.io 的类

c++ - 将多波段 tiff 图像加载到 OpenCV C++ 中

opencv - 使用opencv确定篮子中红苹果的数量