gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:34:22 26 4
gpt4 key购买 nike

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

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/

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