python - 距离变换 - 该功能无法正常工作

标签 python opencv distance

我正在尝试获取距离变换图像,但结果很糟糕。

图片:

enter image description here

代码:

import cv2
import imutils
import numpy as np

photo = 'dog.jpg'

img = cv2.imread(photo)
ybprc = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
inrangeHsv = cv2.inRange(ybprc, np.array([0, 135, 85]), np.array([255, 180, 135]))
retval, otsu = cv2.threshold(inrangeHsv, 150, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cnts = cv2.findContours(otsu.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c = max(cnts, key=cv2.contourArea)
mask = cv2.drawContours(otsu, [c], -1, (0,255,0), 2)
out = cv2.distanceTransform(mask, distanceType=cv2.DIST_L2, maskSize=5)

cv2.imshow("distance_transform", out)
cv2.waitKey(0)
cv2.destroyAllWindows()

结果是: enter image description here

但结果应该更像:

enter image description here

我该如何解决?

最佳答案

您的问题是 imshow() 无法正确显示图像。你需要做 imwrite()。

这对我来说适用于 Python/OpenCV。

输入:

enter image description here

import cv2
import numpy as np

# read input
img = cv2.imread('dog.jpg')

# convert to YCbCr
ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)

# use inRange thresholding
thresh = cv2.inRange(ycrcb, np.array([0, 135, 85]), np.array([255, 180, 135]))

# get outer contour
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
big_contour = max(cnts, key=cv2.contourArea)

# draw filled contour on black background
filled = np.zeros_like(thresh)
cv2.drawContours(filled, [big_contour], -1, (255), cv2.FILLED)

# get distance transform
result = filled.copy()
result = cv2.distanceTransform(result, distanceType=cv2.DIST_L2, maskSize=3, dstType=cv2.CV_8U)

# stretch to full dynamic range
result2 = cv2.normalize(result, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

# save result
cv2.imwrite('dog_thresh.png', thresh)
cv2.imwrite('dog_filled_contour.png', filled)
cv2.imwrite('dog_distance.png', result)
cv2.imwrite('dog_distance_normalized.png', result2)

# show results
# note result image will look binary
cv2.imshow("thresh", thresh)
cv2.imshow("filled", filled)
cv2.imshow("result", result)
cv2.waitKey(0)
cv2.destroyAllWindows()


阈值图像:

enter image description here

填充轮廓:

enter image description here

距离结果:

enter image description here

归一化距离结果:

enter image description here

关于python - 距离变换 - 该功能无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61716670/

相关文章:

python - 如何集成 Python mido 和 asyncio?

math - 绘制拟合线(OpenCV)

opencv - 如何建立OpenCV范例

mysql - 如何在不使用几何类型的情况下在 MySQL 中获得更高的计算距离精度?

python - 计算图像中两个像素之间的距离

php - mysql查询中的距离计算

python - 将模式替换为Python中的连续数字字符串

python - pip 选项 "--force-reinstall"是否重新编译模块? (我正在尝试重新安装cx_Oracle)

python - 如何在 Python2 和 3 上打开一个已知编码的文件?

python - 错误 : OpenCV(4. 1.0) 错误 : (-215:Assertion failed) ! ssize.empty() 函数 'cv::resize'