python - 使用 Voronoi 中心测量复杂形状

标签 python opencv numpy voronoi

我目前正在开展一个项目,使用 opencv 和 python 尽可能准确地测量通常弯曲的物体,例如下面显示的箭头。

Curved arrow

我认为一种策略可能是使用 scipy Voronoi 函数来获取沿箭头中心脊柱的点,但现在遇到了麻烦。这是我的代码:

img = cv2.imread('example_rubystreak_2.PNG')
img.shape
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray,190,255,cv2.THRESH_BINARY)
countimage, contours, hierarchy = cv2.findContours(thresh,1,2)
blank = np.zeros((img.shape[0],img.shape[1],1),np.uint8)
#get max length contour
max_contour = 0
contour_idx = None
for ii in range(len(contours)):
    if len(contours[ii]) > max_contour:
        contour_idx = ii
        max_contour = len(contours[ii])
cv2.drawContours(blank,contours,contour_idx,255,cv2.FILLED,8,hierarchy)
apdp = cv2.approxPolyDP(contours[contour_idx],1,True)
ap = [(a[0][0],a[0][1]) for a in apdp]
vor_ap = Voronoi(ap)
spined = []
for ridge in vor_ap.ridge_vertices:
    if cv2.pointPolygonTest(cnt,tuple(vor_ap.vertices[ridge[0]]),True) <= 0.0 or cv2.pointPolygonTest(cnt,tuple(vor_ap.vertices[ridge[1]]),True) <= 0.0:
        continue
    else:
        if tuple(vor_ap.vertices[ridge[0]]) not in spined:
            spined.append([tuple(vor_ap.vertices[ridge[0]].tolist()),cv2.pointPolygonTest(cnt,tuple(vor_ap.vertices[ridge[0]]),True)])
        if tuple(vor_ap.vertices[ridge[1]]) not in spined:
            spined.append([tuple(vor_ap.vertices[ridge[1]].tolist()),cv2.pointPolygonTest(cnt,tuple(vor_ap.vertices[ridge[1]]),True)])
plt.figure(figsize=(12,12))
plt.scatter([s[0][0] for s in spined],[s[0][1] for s in spined])
plt.plot([a[0] for a in ap],[a[1] for a in ap])

生成这张图片的原因:

Voronoi Arrow

有人知道如何使用这些中心点测量箭头的长度吗?我试过使用 np.polyfit 并查看了页面 here但无法找到一种方法来始终如一地获得最中心点描绘的曲线,因为箭头有时像 S 一样弯曲或具有不同形状的点。任何帮助将非常感激。谢谢。

最佳答案

以下是我尝试的概述:

1) 通过使用三次 B 样条插值点来找到中心曲线的参数化表示。使用 scipy.interpolate.splrep。您可能需要删除不遵循中心曲线的离群点以获得良好的三次样条拟合。

2) 获得三次样条曲线后,您可以使用微积分中的弧长积分公式求出弧长,并根据曲线端点的积分限值计算该积分。为此,您需要获得样条曲线的 X 和 Y 一阶导数,scipy.interpolate.splevscipy.interpolate.spalde 应该能够给你。对由 Numpy 数组表示的函数使用 scipy 数值积分例程。

关于python - 使用 Voronoi 中心测量复杂形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867969/

相关文章:

image-processing - opencv 3D模板匹配

python - 如何使我修改后的 pandas/numpy .where 函数适应不同大小的列表参数?

python - 如何从一维数组中获得正确的波峰和波谷

python - 如何从 Python 使用 Perl 库?

python - Microsoft Azure情感API返回[ "statusCode": 404, "message": "Resource not found"]错误

python - pytest 不会运行子目录中的测试文件

python - AttributeError: 'NoneType'对象没有属性 'shape'/从多个轮廓框转换为单数

python - Python中的Null或None函数

Python MySQL-查询被意外缓存

python - 使用数组元组中的列构建 DataFrame