我正在尝试使用距离变换来绘制轮廓,但出现错误:
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:
编辑后的结果:
看起来不正确,还是可以?
最佳答案
问题是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
:我不确定这是否是您的预期结果。
您正在与小狗一起在图像上应用距离变换。
mask
:关于python - 函数 'distanceTransform'中的错误-使用OpenCV(3.4.9)的Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61204462/