点集求凸包的问题经常会遇到,https://www.geeksforgeeks.org/orientation-3-ordered-points/ 给出了一种思路,有空了再仔细研究,本文总结了opencv中相关的方法并给出一个实例。
1、opencv接口
hull = cv.convexHull(points[, hull[, clockwise[, returnPoints]]])
参数说明:
- points:点集。需要注意的是,该参数输入的坐标系是向右为X,向上为Y,和迪卡尔坐标系是相同的,而opencv中的图像坐标系是向右为X,向下为Y,即图像的左上角坐标为(0,0)。
- clockwise:如果设置为True,输出的凸包是顺时针的,如果设置为False,输出的凸包是逆时针的。
- returnPoints:如果设置为True,返回凸包的点坐标,如果设置为False,输出凸包点在点集points中的序号。
2、示例
代码如下:
# encoding:utf-8
import numpy as np
import cv2
import matplotlib.pyplot as plt
axis_list = [[3,1],[2,2],[3,3],[4,4],[2,4],[2,3],[1,2],[2,2],[2,1]]
axis_list = np.array(axis_list)
hull = cv2.convexHull(axis_list,clockwise=True,returnPoints=True)
print(hull)
hull = np.squeeze(hull)
plt.scatter(axis_list[:,0],axis_list[:,1])
plt.plot(hull[:,0],hull[:,1],"r")
plt.plot([hull[-1,0],hull[0,0]],[hull[-1,1],hull[0,1]],"r")
plt.show()
计算结果如下图所示,其中蓝色点是点集,红色线条是凸包轮廓。