OPENCV系列博客主要记录自己学习OPENCV的历程,以及存储已经实现的代码,以备后续回顾使用,代码中包含了主要的备注。
一. 轮廓发现原理:
二.代码展示
#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>
using namespace std;
using namespace cv;
/*This project is to do the contour searching in OpenCV learning*/
Mat src, temp, dst;
const char* INPUT_T = "input image"; //设定图片窗口名称
const char* OUTPUT_T = "Output image";
const char* match_T = "Matching image";
const char* TEMP_T = "Template image";
int threshold_value = 100;
int threshold_max = 255;
void Contour_demo(int, void*); // 声明Matching子函数
int main(int argc, char** argv) {
//Step1 读取并显示原始图片,Temp图像
src = imread("E:/OpenCVLearning/Project/source_image/fish.png");
if (src.empty()) {
printf("could not load image...\n");
return -1;
}
namedWindow(INPUT_T, CV_WINDOW_AUTOSIZE);
namedWindow(OUTPUT_T, CV_WINDOW_AUTOSIZE);
imshow(INPUT_T, src);
cvtColor(src, src, CV_BGR2GRAY); //将原始图片转化为灰度图
//Step2 创建trackbar并且,通过bar调整canny的阈值
const char* trackbar_title = "Canny_threshold";
createTrackbar(trackbar_title, OUTPUT_T, &threshold_value, threshold_max, Contour_demo); //(trackbar名称,trackbar所在窗口,方法,极大值,执行子函数名)
Contour_demo(0, 0);
waitKey(0);
return 0;
}
void Contour_demo(int, void*) {
//Step3 使用Canny方法,提取边缘
Mat canny_output;
Canny(src, canny_output, threshold_value, threshold_value * 2, 3, false);
//Step4 使用findContour 方法,提取轮廓
vector<vector<Point>> contours; //!!轮廓是由一系列点组成的,所以findContour处理生成的轮廓存储其中
vector<Vec4i> hierachy; //!!通过树形结构查找轮廓
findContours(canny_output, contours, hierachy,RETR_TREE,CHAIN_APPROX_SIMPLE,Point(0,0)); //轮廓不偏移
//Step5 使用drawContour 方法,绘制轮廓
dst = Mat::zeros(src.size(), CV_8SC3); //指定dst的尺寸和数据结构
Scalar color =Scalar(128,128,128);
for (size_t i = 0; i < contours.size(); i++) { //轮廓是以数组方式存储的,因此需要遍历提取
drawContours(dst, contours, i, color,2,8, hierachy,0, Point(0, 0)); //Contour中的第i个轮廓
imshow(OUTPUT_T, dst);
}
}
三.最终效果