python - 如何找到不同角度的两个同心轮廓之间的距离?

标签 python opencv image-processing

我有一个带有两个轮廓的图像,其中一个轮廓总是在另一个轮廓“内部”。我想找到 90 个不同角度的两个轮廓之间的距离(意思是每 4 度的距离)。我该怎么做?

这是一个示例图像:

enter image description here

谢谢!

最佳答案

在下面的代码中,我只是给你垂直线的例子,其余的可以通过旋转线来获得。结果是这样的,不用画图,可以用坐标来计算距离。

enter image description here

import shapely.geometry as shapgeo
import numpy as np
import cv2


img = cv2.imread('image.jpg', 0)
ret, img =cv2.threshold(img, 128, 255, cv2.THRESH_BINARY)

#Fit the ellipses
_, contours0, hierarchy = cv2.findContours( img.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
outer_ellipse = [cv2.approxPolyDP(contours0[0], 0.1, True)]
inner_ellipse = [cv2.approxPolyDP(contours0[2], 0.1, True)]

h, w = img.shape[:2]
vis = np.zeros((h, w, 3), np.uint8)
cv2.drawContours( vis, outer_ellipse, -1, (255,0,0), 1)
cv2.drawContours( vis, inner_ellipse, -1, (0,0,255), 1)

##Extract contour of ellipses
cnt_outer = np.vstack(outer_ellipse).squeeze()
cnt_inner = np.vstack(inner_ellipse).squeeze()

#Determine centroid
M = cv2.moments(cnt_inner)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
print cx, cy

#Draw full segment lines 
cv2.line(vis,(cx,0),(cx,w),(150,0,0),1)

# Calculate intersections using Shapely
# http://toblerity.org/shapely/manual.html
PolygonEllipse_outer= shapgeo.asLineString(cnt_outer)
PolygonEllipse_inner= shapgeo.asLineString(cnt_inner)
PolygonVerticalLine=shapgeo.LineString([(cx,0),(cx,w)])


insecouter= np.array(PolygonEllipse_outer.intersection(PolygonVerticalLine)).astype(np.int)
insecinner= np.array(PolygonEllipse_inner.intersection(PolygonVerticalLine)).astype(np.int)
cv2.line(vis,(insecouter[0,0], insecinner[1,1]),(insecouter[1,0], insecouter[1,1]),(0,255,0),2)
cv2.line(vis,(insecouter[0,0], insecinner[0,1]),(insecouter[1,0], insecouter[0,1]),(0,255,0),2)

cv2.imshow('contours', vis)

0xFF & cv2.waitKey()
cv2.destroyAllWindows()  

关于python - 如何找到不同角度的两个同心轮廓之间的距离?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504073/

相关文章:

python - 卷积并合并到输入图像后如何计算输出大小

python - 用不同的方法寻找候选板 block

ios - 如何拍摄模糊的照片(例如从 iPad 2 拍摄的照片)并使用 iOS API 对其进行锐化?

javascript - 如何在 HTML 图像中查找圆圈并注册悬停事件?

python - 使用坐标列表进行索引的更多 Pythonic 方法

python - 通过从 SQL DB 导入的 pd 数据帧的子集提高循环性能

python - python 中有没有不用字典就可以计算音节的方法?

c++ 3D matrix using vector 性能不佳

c++ - OpenCV 在鼠标移动时停止渲染

c# - 如何解决这个问题 `OpenCV: scale factor must be > 1…`?在OpenCV中总结?