找最小的封闭轮廓的图像

来源:互联网 发布:西科软件培训中心 编辑:程序博客网 时间:2024/05/01 16:44
#include <opencv2/opencv.hpp>#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc/imgproc.hpp>using namespace std;using namespace cv;static vector<vector<Point> > contours;static vector<Vec4i> heirarchy;Mat img_all_contours;static void make_contours_closed(vector<vector<Point> > contours) {for(int i = 0; i < contours.size(); i++) {vector<Point> cc;approxPolyDP(contours[i], cc, 0.1, true);contours[i] = cc;}}static int smallest_contour(Point p, vector<vector<Point> > contours, vector<Vec4i> heirarchy) {int idx = 0, prev_idx = -1;while(idx >= 0) {vector<Point> c = contours[idx];// Point polygon testdouble d = pointPolygonTest(c, p, false);// If point is inside the contour, move to its child... if(d > 0) {prev_idx = idx;idx = heirarchy[idx][2];}//...else check the next cotour at the same levelelse idx = heirarchy[idx][0];}return prev_idx;}static void on_mouse(int event, int x, int y, int, void *) {if(event != EVENT_LBUTTONDOWN) return;Point p(x, y);int idx = smallest_contour(p, contours, heirarchy);// If function returned a valid contour index, draw it using a thick red lineif(idx > 0) {vector<vector<Point> > contour_show(1, contours[idx]);Mat img_show = img_all_contours.clone();drawContours(img_show, contour_show, -1, Scalar(0, 0, 255), 3);imshow("Contours", img_show);}elseimshow("Contours", img_all_contours);}extern int main() {//const char *fileName = "捕获7.JPG";const char *fileName = "Brox_Effect_000012.jpg";Mat img = imread(fileName);if (img.empty()){fprintf(stderr, "Load picture failed!\n");return 1;}imshow("原始图",img);Mat edges;Canny(img, edges, 50, 100);/************************************************************************//* //Contour retrieval modesenum{CV_RETR_EXTERNAL = 0,CV_RETR_LIST = 1,CV_RETR_CCOMP = 2,CV_RETR_TREE = 3,CV_RETR_FLOODFILL = 4};//Contour approximation methodsenum{CV_CHAIN_CODE = 0,CV_CHAIN_APPROX_NONE = 1,CV_CHAIN_APPROX_SIMPLE = 2,CV_CHAIN_APPROX_TC89_L1 = 3,CV_CHAIN_APPROX_TC89_KCOS = 4,CV_LINK_RUNS = 5};void findContours(InputOutputArray image, OutputArrayOfArrays contours,OutputArray hierarchy, int mode,int method, Point offset = Point());*//************************************************************************/findContours(edges, contours, heirarchy, CV_RETR_TREE, CV_CHAIN_APPROX_TC89_L1);// Make the contours closedmake_contours_closed(contours);img_all_contours = img.clone();// Draw all contours using a thin green linedrawContours(img_all_contours, contours, -1, Scalar(0, 255, 0));namedWindow("Contours", CV_WINDOW_AUTOSIZE);imshow("Contours", img_all_contours);setMouseCallback("Contours", on_mouse);while(char(waitKey(1)) != 'q') {}return 0;}

0 0
原创粉丝点击