今天分享一个使用OpenCV给轮廓排序的例子,排序是依据轮廓面积的大小,当然你还可以改成其他的,比如宽高,长度等。
先看下原图包含4个不同大小的矩形:
上代码(Python OpenCV):
import cv2 import numpy as np # putText函数使用的字体定义 font = cv2.FONT_HERSHEY_SIMPLEX PI = 3.1415926 # 读取图片、灰度转换、OTSU阈值 img = cv2.imread("test.png") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU) # 查看二值化结果 cv2.imshow("thres", thresh) cv2.imwrite("thres.jpg", thresh) # 轮廓查找 _, contours,hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) def cnt_area(cnt): area = cv2.contourArea(cnt) return area contours.sort(key = cnt_area, reverse=False) for i in range(0, len(contours)): (x, y, w, h) = cv2.boundingRect(contours[i]) cv2.rectangle(img,(x,y),(x+w, y+h),(255,0,0),2, cv2.LINE_AA) cv2.putText(img,"No.%d"%(i+1),(x,y-5),font,0.8,(255,0,0),2) cv2.imshow("contours", img) cv2.imwrite("result1.jpg",img) cv2.waitKey(0) cv2.destroyAllWindows()核心函数如下,对contours list排序:
def cnt_area(cnt): area = cv2.contourArea(cnt) return area contours.sort(key = cnt_area, reverse=False)reverse=False(默认)降序排列,reverse=True升序排列
效果如如下:
C++ OpenCV代码类似,如下:
//比较轮廓面积(USB_Port_Lean用来进行轮廓排序) bool Contour_Area(vector<Point> contour1, vector<Point> contour2) { return contourArea(contour1) > contourArea(contour2); }vector<vector<Point>> contours; vector<Vec4i> hierarcy; bool ret = false; findContours(thres, contours, hierarcy, RETR_EXTERNAL, CHAIN_APPROX_NONE); //查找轮廓 sort(contours.begin(), contours.end(), Contour_Area); for (int i = 0; i < contours.size(); i++) { double area = contourArea(contours[i]); cout << area << endl; } ---来自腾讯云社区的---Color Space
微信扫一扫打赏
支付宝扫一扫打赏