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/

相关文章:

ios - 两个图像的多重混合动画

python - 如何将flask_login 与多个用户类和不同的数据库条目一起使用?

python - 在生产环境中管理 django 项目的推荐方法是什么(在 apache 服务器中)

python - 如何使用opencv获得图像蒙版后模糊图像?

c# - 人脸检测EmguCV

c++ - 如何从图像中删除矩形轮廓

algorithm - 线组之间的距离

python - 如何用字典修复一些 pandas 列值并保留其他列值?

python - 当我限制 "threads"的数量时,我在设置什么?

python - 在 python 和 openCV 中实现 LoG blob 检测器