引言
在图像处理中,对物体轮廓进行排序是一项常见任务。本文介绍了如何利用OpenCV对图像中的物体轮廓进行排序,并实现可视化结果。
读取图像
首先,读取图像并生成边缘检测图。
<code>image = cv2.imread(args['image']) accumEdged = np.zeros(image.shape[:2], dtype='uint8') for chan in cv2.split(image): chan = cv2.medianBlur(chan, 11) edged = cv2.Canny(chan, 50, 200) accumEdged = cv2.bitwise_or(accumEdged, edged) cv2.imshow('Edge Map', accumEdged)</code>
获取轮廓
利用OpenCV的findContours函数获取图像中的轮廓。
<code>cnts = cv2.findContours(accumEdged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = grab_contours(cnts) cnts = sorted(cnts, key=cv2.contourArea, reverse=True)[:5] orig = image.copy() # unsorted for (i, c) in enumerate(cnts): orig = draw_contour(orig, c, i) cv2.imshow('Unsorted', orig) cv2.imwrite("./Unsorted.jpg", orig)</code>
轮廓排序
实现对轮廓进行排序的函数sort_contours。
<code>def sort_contours(cnts, method='left-to-right'): reverse = False i = 0 if method == 'right-to-left' or method == 'bottom-to-top': reverse = True if method == 'bottom-to-top' or method == 'top-to-bottom': i = 1 boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse)) return (cnts, boundingBoxes)</code>
轮廓排序及可视化
调用排序函数,并显示排序后的结果。
<code>(cnts, boundingboxes) = sort_contours(cnts, method=args['method']) for (i, c) in enumerate(cnts): image = draw_contour(image, c, i) cv2.imshow('Sorted', image) cv2.waitKey(0)</code>
总结
通过本文介绍的方法,您可以利用OpenCV对图像中的物体轮廓进行排序,并实现不同排序顺序的可视化效果。
© 版权声明
THE END
暂无评论内容