使用OpenCV 3和python 3对其图像轮廓进行排序的最佳解决方案

时间:2017-11-17 15:31:39

标签: python sorting opencv image-processing

使用OpenCV 3和Python 3对图像中的轮廓进行排序的最佳(最佳)解决方案是什么? 我试试这个。这是最好的解决方案吗?

_, contours, _ = cv2.findContours(image , cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
areas = list(map(lambda c : cv2.contourArea(c), contours))
contoursWithAreas = zip(contours, areas)
sortedContoursWithArea = sorted(contoursWithAreas, key=lambda s : s[1])
sortedContours ,sortedAreas = zip(*sortedContoursWithArea)

最后,我们按照sortedContours变量中的区域对轮廓进行了排序。

1 个答案:

答案 0 :(得分:1)

众所周知,轮廓是np.ndarray的列表。所以我们不能避免使用numpy。那么为什么不使用np.argsort()

cnts = cv2.findContours(threshed, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]
areas = np.array([cv2.contourArea(cnt) for cnt in cnts])
idxs  = areas.argsort()
cnts2 = [cnts[i] for i in idxs]