获取二进制图像的坐标,并从一个点开始按顺时针方向对其进行排序

时间:2019-05-10 09:13:39

标签: python image opencv matplotlib

我正在处理代表轮廓的二进制图像(通过cv2.Canny拍摄),我想顺时针获取每个轮廓的坐标,从作为图像与位于图像的中心。假设我要使用的图像是圆形轮廓,我想得到这样的图像(假设Y像matplotlib.pyplot.imshow那样垂直减小): Wanted Behaviour 我尝试使用以下代码:

indices = numpy.where(edges == [255]) #edges is the contour image
print(indices)

但是此解决方案从图像的上侧对坐标进行排序。我也尝试了在网络上找到的其他解决方案,但是似乎没有一个解决方案可用于此任务。

1 个答案:

答案 0 :(得分:2)

我将结合numpy中的that answer函数,从arctan2中回收想法。

给出的输入图像如下:

Input circle

输出将是这样的图:

Plot circle

下面是代码,希望可以自己解释一下:

import cv2
import numpy as np
import matplotlib.pyplot as plt

# Generate artificial image
img = np.zeros((400, 400), np.uint8)
center = (150, 150)
img = cv2.circle(img, center, 100, 255, 1)
cv2.imwrite('images/img.png', img)

# Find contour(s)
cnts, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# Center contour
cnt = np.squeeze(cnts[0]) - center

# Calculate atan2 values, and sort
val = np.sort(np.arctan2(cnt[:, 0], cnt[:, 1]))
idx = np.argsort(np.arctan2(cnt[:, 0], cnt[:, 1]))

# atan2 uses (1, 0) as starting point, so correct by 1/2 * pi
corr = np.where(val <= (-0.5 * np.pi))[0][-1]

# Build final indices
indFinal = np.concatenate((idx[corr - 1:], idx[0:corr]))
x = cnt[indFinal, 0]
y = cnt[indFinal, 1]

# Generate plot
ax = plt.subplot(121)
plt.plot(x)
plt.title('x')
ax = plt.subplot(122)
plt.plot(y)
plt.title('y')
plt.savefig('images/plot.png')

凹面:凹面轮廓可能会导致结果损坏。