Opencv轮廓计数(学习)
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
using namespace std;
using namespace cv;
using namespace cv::xfeatures2d;
Mat img1, img2, img3, img4, img5, img6, img_result, img_gray1, img_gray2, img_gray3, img_canny1, img_binary1, img_binary2, img_dist1, img_dist2, kernel_1, kernel_2, img_laplance, img_sharp;
char win1[] = "window1";
char win2[] = "window2";
char win3[] = "window3";
char win4[] = "window4";
char win5[] = "window5";
char win6[] = "window6";
char win7[] = "window7";
int thread_value = 10;
int max_value = 255;
RNG rng1(12345);
RNG rng2(1235);
double harris_min = 0;
double harris_max = 0;
int Demo_SURF();
void Demo_1(int, void*);
void Demo_2(int, void*);
int Demo_SURF()
{
namedWindow(win1, CV_WINDOW_AUTOSIZE);
//namedWindow(win2, CV_WINDOW_AUTOSIZE);
//namedWindow(win3, CV_WINDOW_AUTOSIZE);
img1 = imread("D://images//71.png");
//img1 = imread("D://images//77.jpg");
if (img1.empty())
{
cout << "could not load image..." << endl;
return 0;
}
imshow(win1, img1);
//转灰度
cvtColor(img1, img_gray1, COLOR_BGR2GRAY);
//二值化
threshold(img_gray1, img_binary1, 0, 255, THRESH_BINARY | THRESH_TRIANGLE);
imshow(win2,img_binary1);
//形态学操作
kernel_1 = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
dilate(img_binary1, img_binary2, kernel_1, Point(-1, -1),1);
imshow(win3, img_binary2);
//背景变换
bitwise_not(img_binary2,img_binary2);
//距离变换
distanceTransform(img_binary2, img2, CV_DIST_L2, 3);
//归一化(0-1)
normalize(img2, img2, 0, 1.0, NORM_MINMAX);
imshow(win4, img2);
//阈值化二值分割
threshold(img2, img2, 0.6, 1.0, THRESH_BINARY);
img2.convertTo(img3, CV_8U);
adaptiveThreshold(img3,img3,255,ADAPTIVE_THRESH_GAUSSIAN_C,THRESH_BINARY,87,0.0);
kernel_2 = getStructuringElement(MORPH_RECT, Size(5, 5), Point(-1, -1));
dilate(img3, img3, kernel_2, Point(-1, -1), 4);
//normalize(img3, img3, 0, 255, NORM_MINMAX);
imshow(win5,img3);
//连通区域
vector<vector<Point>> vec_contours;
findContours(img3, vec_contours, CV_RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
img4 = Mat::zeros(img1.size(),CV_8UC3);
//绘制轮廓
for (size_t k=0;k<vec_contours.size();k++)
{
Scalar color_1 = Scalar(rng1.uniform(0,255),rng1.uniform(0,255),rng1.uniform(0,255));
drawContours(img4, vec_contours, static_cast<int>(k), color_1, 2, 8,Mat());
}
cout << "size:"<<vec_contours.size() << endl;
imshow(win6,img4);
return 0;
}
void Demo_1(int, void*)
{
}
void Demo_2(int, void*)
{
}
int main()
{
Demo_SURF();
waitKey(0);
return 0;
}