1. 程式人生 > >獲取最大輪廓 opencv

獲取最大輪廓 opencv

#include<iostream>    
#include <opencv2/core/core.hpp>      
#include <opencv2/highgui/highgui.hpp>   
#include<imgproc/imgproc.hpp>    

using namespace std;  
using namespace cv;  

int main(){  

    Mat image = cvLoadImage("group.jpg");  
    Mat grayImage;  
    cvtColor(image, grayImage, CV_BGR2GRAY);  
    //轉換為二值圖    
Mat binaryImage; threshold(grayImage, binaryImage, 90, 255, CV_THRESH_BINARY); //二值圖 這裡進行了畫素反轉,因為一般我們用255白色表示前景(物體),用0黑色表示背景 Mat reverseBinaryImage; bitwise_not(binaryImage, reverseBinaryImage); vector <vector<Point>>contours; findContours(reverseBinaryImage, contours, //輪廓的陣列
CV_RETR_EXTERNAL, //獲取外輪廓 CV_CHAIN_APPROX_NONE); //獲取每個輪廓的每個畫素 //在白色影象上繪製黑色輪廓 Mat result(reverseBinaryImage.size(), CV_8U, Scalar(255)); drawContours(result, contours, -1, //繪製所有輪廓 Scalar(0), //顏色為黑色 2); //輪廓線的繪製寬度為2 namedWindow("contours"
); imshow("contours", result); //移除過長或過短的輪廓 int cmin = 100; //最小輪廓長度 int cmax = 1000; //最大輪廓 vector<vector<Point>>::const_iterator itc = contours.begin(); while (itc!=contours.end()) { if (itc->size() < cmin || itc->size() > cmax) itc = contours.erase(itc); else ++itc; } //在白色影象上繪製黑色輪廓 Mat result_erase(binaryImage.size(), CV_8U, Scalar(255)); drawContours(result_erase, contours, -1, //繪製所有輪廓 Scalar(0), //顏色為黑色 2); //輪廓線的繪製寬度為2 namedWindow("contours_erase"); imshow("contours_erase", result_erase); waitKey(0); return 0; }

這裡寫圖片描述