// opencv_1.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include
#include
#include
#include
using namespace cv;
using namespace std;
int main()
{
system("color 1A");
Mat srcImage = imread("E:\\pictures\\For_Project\\New_opencv\\sunsun.jpg",0);
if (!srcImage.data) {
cout << "读取图片错误,请确定该目录下是否存在该对应图片。" << endl;
return false;
}
imshow("【原图二值图】", srcImage);
//初始化结果图
Mat dstImage = Mat::zeros(srcImage.rows, srcImage.cols, CV_8UC3);
//srcImage取阈值大于119的部分
srcImage = srcImage > 119;
imshow("【阈值原图】", srcImage);
//定义轮廓和层次结构
vector> contours;
vector hierarchy;
//查找轮廓
findContours(srcImage, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE);
//遍历所有顶层的轮廓,随机绘制颜色,绘制出每个连接组件的颜色
int index = 0;
for (;index >= 0;index = hierarchy[index][0]) {
Scalar color(rand() & 255, rand() & 255, rand() & 255);
drawContours(dstImage, contours, index, color, FILLED, 8, hierarchy);
}
imshow("【轮廓图】", dstImage);
while((char)waitKey(0)!='q'){}
return 0;
}
综合例子:
// opencv_1.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include
#include
#include
#include
using namespace cv;
using namespace std;
#define WINDOW_NAME_1 "【原始窗口】"
#define WINDOW_NAME_2 "【轮廓图】"
Mat g_srcImage, g_grayImage;
int g_nThresh = 80;
int g_nThresh_max = 255;
RNG g_rng(12345);
Mat g_cannyMat_output;
vector> g_vContours;
vector g_vHierarchy;
void on_ThreshChange(int, void*);
int main()
{
system("color 1A");
Mat srcImage = imread("E:\\pictures\\For_Project\\New_opencv\\Lena.jpg",1);
if (!srcImage.data) {
cout << "读取图片错误,请确定该目录下是否存在该对应图片。" << endl;
return false;
}
imshow("【原图二值图】", srcImage);
g_srcImage = srcImage.clone();
//转化为灰度图并模糊化降噪
cvtColor(g_srcImage, g_grayImage, COLOR_BGR2GRAY);
blur(g_grayImage, g_grayImage, Size(3, 3));
//创建窗口
namedWindow(WINDOW_NAME_1, WINDOW_AUTOSIZE);
imshow(WINDOW_NAME_1, g_srcImage);
//创建滚动条并初始化
createTrackbar("canny阈值", WINDOW_NAME_1, &g_nThresh, g_nThresh_max, on_ThreshChange);
on_ThreshChange(0, 0);
while((char)waitKey(0)!='q'){}
return 0;
}
void on_ThreshChange(int, void*) {
//使用canny算子检测边缘
Canny(g_grayImage, g_cannyMat_output, g_nThresh, g_nThresh * 2, 3);
//寻找轮廓
findContours(g_cannyMat_output, g_vContours, g_vHierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE, Point(0, 0));
//绘制轮廓
Mat drawing = Mat::zeros(g_cannyMat_output.size(), CV_8UC3);
for (int i = 0;i < g_vContours.size();i++) {
Scalar color = Scalar(g_rng.uniform(0, 255), g_rng.uniform(0, 255), g_rng.uniform(0, 255));
drawContours(drawing, g_vContours, i, color, 2, 8, g_vHierarchy, 0, Point());
}
imshow(WINDOW_NAME_2, drawing);
}