首页 > 解决方案 > 取决于轮廓的像素距离

问题描述

我在 opencv 中有一个二进制图像,其中显示了对象的轮廓。我的老板告诉我,OpenCV 中有一个函数可以测量图像的所有像素与轮廓之间的最小距离,有人能告诉我这个函数是什么吗?或者,如果有一个内核可用于对该图像执行卷积?

要了解我的目标是什么:水图像介绍

谢谢

标签: c++opencv

解决方案


我认为这是cv2.distanceTransform计算与轮廓的距离。

distanceTransform(...)
    distanceTransform(src, distanceType, maskSize[, dst[, dstType]]) -> dst
    .   @overload
    .   @param src 8-bit, single-channel (binary) source image.
    .   @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
    .   single-channel image of the same size as src .
    .   @param distanceType Type of distance, see #DistanceTypes
    .   @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the
    .   #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives
    .   the same result as \f$5\times 5\f$ or any larger aperture.
    .   @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for
    .   the first variant of the function and distanceType == #DIST_L1.

一个简单的例子(在python中)在这里:

import numpy as np
import matplotlib.pyplot as plt 

img = np.zeros((400, 800), np.uint8)
cv2.circle(img, (300, 200), 100, (255,0,0), 3, cv2.LINE_AA)
cv2.circle(img, (500, 200), 100, (255,0,0), 3, cv2.LINE_AA)
img = 255 - img
#cv2.imshow("x", img);cv2.waitKey();cv2.destroyAllWindows()
dist = cv2.distanceTransform(img, cv2.DIST_L2, maskSize=0)
plt.subplot(211)
plt.imshow(img, cmap="gray")
plt.subplot(212)
plt.imshow(dist)
plt.show()

在此处输入图像描述

一个 C++ 示例在这里:

沿其整个长度的轮廓宽度测量


推荐阅读