close
1: cvtColor(imgSrc, imgG, CV_BGR2GRAY);
2: threshold(imgG, imgBW, 100, 255, THRESH_BINARY);
3: vector<vector<Point>> contours;
4: vector<Vec4i> hierarchy;
5:
6: findContours(imgBW, contours, hierarchy, RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
下圖中如果邊緣為垂直或水平線,則只會取端點;其他狀況則會沿著邊緣取出。
1: for (int i = 0; i < contours.size(); i++) {
2: cout << "contour # " << i << endl;
3: // 點
4: for (int j = 0; j < contours[i].size(); j++)
5: {
6: Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255) );
7: circle(imgDst, contours[i][j], 4, color, 2, 8);
8: }
9: drawContours(imgDst2, contours, i, Scalar(0, 0, 255),2);
10: drawContours(imgDst3, contours, i, Scalar(0, 0, 255), -1);
11:
12: cout << contours[i] << endl;
13: }
如果只想找外輪廓呢?
1: findContours(imgBW, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE);
--------------------
計算每一個物體的平均像素值
遮罩應用
1:
2: for (int i = 0; i < contours.size(); i++) {
3: cout << "contour # " << i << endl;
4: imgMask = Mat::zeros(imgSrc.size(), CV_8UC1);
5: drawContours(imgMask, contours, i, Scalar(255), -1);
6: Mat imgROI;
7: imgSrc.copyTo(imgROI, imgMask);
8: string name = std::to_string(i);
9: imshow(name, imgROI);
10: }
每一個物件(套用遮罩)的平均像素值
1: cout << "mean = " << mean(imgSrc, imgMask) << endl;
參考資料
全站熱搜
留言列表