尋找和繪製物體凸包
阿新 • • 發佈:2018-11-22
1、尋找凸包函式
void convexHull(InputArray Point,OutputArray hull,bool clockwise=false,bool returnPoints=true)
引數一:輸入的二維點集,可以是Mat或者是std:vector
引數二:輸出引數,函式呼叫後的輸出的凸包
引數三:為真輸出的凸包順時針方向,為假輸出的凸包逆時針
引數四:為真返回個凸包的各個點,為假返回凸包的指數。若輸出陣列型別是std:vector是忽略該標誌
示例:
-------來自opencv3入門程式設計 毛星雲pdf#include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #define WINDOW_NAME1 "【原始圖】" #define WINDOW_NAME2 "【效果圖】" using namespace std; using namespace cv; Mat g_srcImage,g_grayImage; int g_Thresh =50; int g_ThreshMax = 255; RNG rng(12345); Mat srcImage_copy = g_srcImage.clone(); Mat g_thresholdImage_output; vector<vector<Point> >g_vContours; vector<Vec4i>g_vHierarchy; void on_ThreshChange(int,void *); int main(int argc,char *argv[]) { if(argc!=2) { cout<<"input error"<<endl; return -1; } g_srcImage = imread(argv[1],1); if(g_srcImage.empty()) { cout<<"read picture fail"<<endl; return -1; } namedWindow(WINDOW_NAME1,WINDOW_AUTOSIZE); namedWindow(WINDOW_NAME2,WINDOW_AUTOSIZE); imshow(WINDOW_NAME1,g_srcImage); cvtColor(g_srcImage,g_grayImage,COLOR_BGR2GRAY); blur(g_grayImage,g_grayImage,Size(3,3)); createTrackbar("閾值:",WINDOW_NAME2,&g_Thresh,g_ThreshMax,on_ThreshChange); on_ThreshChange(0,0); waitKey(0); return 0; } void on_ThreshChange(int,void *) { threshold(g_grayImage,g_thresholdImage_output,g_Thresh,255,THRESH_BINARY); findContours(g_thresholdImage_output,g_vContours,g_vHierarchy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point(0,0)); vector<vector<Point> > hull(g_vContours.size()); for(int i=0;i<g_vContours.size();i++) { convexHull(Mat(g_vContours[i]),hull[i],false); } Mat drawing = Mat::zeros(g_thresholdImage_output.size(),CV_8UC3); for(unsigned int i=0;i<g_vContours.size();i++) { Scalar color = Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)); drawContours(drawing,g_vContours,i,color,1,8,vector<Vec4i>(),0,Point()); drawContours(drawing,hull,i,color,1,8,vector<Vec4i>(),0,Point()); } imshow(WINDOW_NAME2,drawing); }