#include<opencv2/opencv.hpp> using namespace cv; void main() { //---繪製點集的凸包 Mat img(400, 400, CV_8UC3, Scalar::all(0)); //定義繪製圖像 RNG rng; //定義隨機數對象 while(1) { char key; int count = (unsigned int)rng % 100; //定義點的個數 vector<Point> points; //定義點集 for(int i=0; i<count; i++) { Point pt; pt.x = rng.uniform(img.cols/4, img.cols*3/4); //設定點的x範圍 pt.y = rng.uniform(img.rows/4, img.rows*3/4); //設定點的y範圍 points.push_back(pt); } //檢測凸包 vector<int> hull; convexHull(Mat(points), hull, true); img = Scalar::all(0); for(int i = 0; i < count; i++ ) circle(img, points[i], 3, Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255)), CV_FILLED, CV_AA); //準備參數 int hullcount = (int)hull.size(); //凸包的邊數 Point point0 = points[hull[hullcount-1]]; //鏈接凸包邊的座標點 //繪製凸包的邊 for(int i = 0; i < hullcount; i++ ) { Point point = points[hull[i]]; circle(img, point, 8, Scalar(0, 255, 0), 2, 8); line(img, point0, point, Scalar(255, 255, 255), 2, CV_AA); point0 = point; } //顯示效果圖 imshow("img", img); //按下ESC,Q,或者q,程序退出 key = (char)waitKey(); if( key == 27 || key == 'q' || key == 'Q' ) break; } 51}
#include<opencv2/opencv.hpp> using namespace cv; void main() { Mat srcImg = imread("E://12.jpg"); imshow("src", srcImg); Mat dstImg2 = srcImg.clone(); Mat tempImg(srcImg.rows, srcImg.cols, CV_8UC3, Scalar::all(0)); //用於繪製凸包 Mat dstImg(srcImg.rows, srcImg.cols, CV_8UC3, Scalar::all(0)); //用於繪製輪廓 cvtColor(srcImg, srcImg, CV_BGR2GRAY); threshold(srcImg, srcImg, 100, 255, CV_THRESH_BINARY); //二值化 vector<vector<Point>> contours; vector<Vec4i> hierarcy; findContours(srcImg, contours, hierarcy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); vector<vector<Point>> hull(contours.size()); for(int i=0; i<contours.size(); i++) { convexHull(Mat(contours[i]), hull[i], true); //查找凸包 drawContours(dstImg, contours, i, Scalar(255, 255, 255), -1, 8); //繪製輪廓 //drawContours(dstImg, hull, i, Scalar(rand()%255, rand()%255, rand()%255), 2, 8); drawContours(tempImg, hull, i, Scalar(255, 255, 255), -1, 8); } imshow("hull", tempImg); imshow("contours", dstImg); Mat diffImg; absdiff(tempImg, dstImg, diffImg); //圖像相減 Mat element = getStructuringElement(MORPH_RECT, Size(3, 3), Point(-1, -1)); erode(diffImg, diffImg, element); imshow("diff", diffImg); vector<vector<Point>> contours2; vector<Vec4i> hierarcy2; cvtColor(diffImg, diffImg, CV_BGR2GRAY); //轉爲灰度圖 threshold(diffImg, diffImg, 100, 255, CV_THRESH_BINARY); //二值化 findContours(diffImg, contours2, hierarcy2, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); drawContours(dstImg2, contours2, -1, Scalar(0, 0, 255), 2, 8); //紅色繪製缺陷輪廓 imshow("defects", dstImg2); waitKey(0); }
原文:http://www.javashuo.com/article/p-osiubbqb-bc.htmlhtml
---spa