輪廓發現(find contour)
l輪廓發現是基于圖像邊緣提取的基礎尋找對象輪廓的方法。
是以邊緣提取的門檻值標明會影響最終輪廓發現結果
lAPI介紹
-findContours發現輪廓
-drawContours繪制輪廓
輪廓發現(find contour)
在二值圖像上發現輪廓使用API cv::findContours(
InputOutputArray binImg, // 輸入圖像,非0的像素被看成1,0的像素值保持不變,8-bit
OutputArrayOfArrays contours,// 全部發現的輪廓對象
OutputArray, hierachy// 圖該的拓撲結構,可選,該輪廓發現算法正是基于圖像拓撲結構實作。
int mode, // 輪廓傳回的模式
int method,// 發現方法
Point offset=Point()// 輪廓像素的位移,預設(0, 0)沒有位移
)
輪廓繪制(draw contour)
在二值圖像上發現輪廓使用API cv::findContours之後對發現的輪廓資料進行繪制顯示
drawContours(
InputOutputArray binImg, // 輸出圖像
OutputArrayOfArrays contours,// 全部發現的輪廓對象
Int contourIdx// 輪廓索引号
const Scalar & color,// 繪制時候顔色
int thickness,// 繪制線寬
int lineType ,// 線的類型LINE_8
InputArray hierarchy,// 拓撲結構圖
int maxlevel,// 最大層數, 0隻繪制目前的,1表示繪制繪制目前及其内嵌的輪廓
Point offset=Point()// 輪廓位移,可選
示範代碼
l輸入圖像轉為灰階圖像cvtColor
l使用Canny進行邊緣提取,得到二值圖像
l使用findContours尋找輪廓
l使用drawContours繪制輪廓
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
Mat src;
int threshold_value = 100;
int threshold_max = 255;
void Demo_Contours(int, void*);
const char * input_image = "input";
const char output_win[] = "output";
int main(int agrc, char** agrv) {
Mat hsvbase, hsvtest1, hsvtest2;
src = imread("C:/Users/liyangxian/Desktop/bjl/nm4.jpg");
if (!src.data) {
printf("no load..\n");
return -1;
}
namedWindow(input_image, CV_WINDOW_AUTOSIZE);
namedWindow(output_win, CV_WINDOW_AUTOSIZE);
imshow(input_image, src);
cvtColor(src, src, CV_BGR2GRAY);
const char * trackbar_title = "Threshold Value:";
createTrackbar(trackbar_title, output_win, &threshold_value, threshold_max, Demo_Contours);
Demo_Contours(0, 0);
waitKey(0);
return 0;
}
void Demo_Contours(int, void*) {
Mat canny_output;
vector<vector<Point>> contours;
vector<Vec4i> hierachy;
Canny(src,canny_output,threshold_value,threshold_value*2,3,false);
findContours(canny_output, contours, hierachy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
Mat dst = Mat::zeros(src.size(), CV_8UC3);
RNG rng(12345);
for (size_t i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
drawContours(dst, contours, i, color, 2, 8, hierachy, 0, Point(0, 0));
}
imshow(output_win, dst);
}