1. 程式人生 > >簡單opencv 外輪廓檢測以加矩形框

簡單opencv 外輪廓檢測以加矩形框

#include <iostream>
#include <opencv2\opencv.hpp>
#include<opencv.hpp>
using namespace std;
using namespace cv;
int main() {
	   Mat threshold_output;
	   vector<vector<Point> > contours;
	   vector<Vec4i> hierarchy;
	   Mat src_gray;
	   Mat frame;
	  //自定義形態學元素結構
	   cv::Mat element5(9, 9, CV_8U, cv::Scalar(1));//5*5正方形,8位uchar型,全1結構元素  
	   Scalar color = Scalar(0, 0, 255);
	   cv::Mat closed;
	   Rect rect;
		frame = imread("./lunkuo.jpg");
		imshow("src", frame);
		Mat image = frame.clone();
		cvWaitKey(1000);
		cvtColor(frame, src_gray, COLOR_BGR2GRAY);
		//使用Canny檢測邊緣  
		Canny(src_gray, threshold_output, 80, 126, (3, 3));
		//高階形態學閉運算函式  
		cv::morphologyEx(threshold_output, closed, cv::MORPH_CLOSE, element5);
		imshow("canny", threshold_output);
		imshow("erode", closed);
		// 尋找外輪廓輪廓  
		findContours(closed, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_NONE, Point());
		cout << contours.size() << endl;
		for (int i = 0; i < contours.size(); i++)
		{

			for (int j = 0; j < contours[i].size(); j++)
			{
			
				cout << contours[i][j] << endl;
				//遍歷輪廓中每個畫素點並且賦值顏色
				//frame.at<Vec3b>(contours[i][j].y, contours[i][j].x) = (0, 0, 255);
			}

		}
	    //轉換輪廓點到最大外矩形框
		rect = boundingRect(contours[0]);
		rectangle(image,rect,color);
		//加矩形框後的圖片
		imshow("rect", image);
		cvWaitKey(0);
	return 0;
}