学习目标:
学习opencv常见的处理图片的函数,包含常规的读取、转灰度图、图像金字塔向上向下采样、高斯模糊、阈值操作、查找轮廓
基本处理图像的操作,熟悉opencv的函数,后期便于识别自己想要图片中的元素,可以根据元素的几何特征过滤轮廓。
直接上代码:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <math.h>
using namespace std;
using namespace cv;
int main (int argc, char** argv) {
if(argc != 2) {
cout<< "need 2 params"<<endl;
return 1;
}
// 读取图像,以灰度图读取
Mat img_1 = imread(argv[1], CV_LOAD_IMAGE_COLOR);
imshow("original1", img_1);
Mat img_gray;
//根据需要将灰度图转化为rgb
cvtColor(img_1,img_gray,CV_BGR2GRAY);
imshow("original1", img_gray);
// 图像金字塔
Mat dst1, proImg1;
pyrDown(img_gray, proImg1, Size(img_1.cols/2, img_1.rows/2));
pyrUp(proImg1, dst1, Size(proImg1.cols*2, proImg1.rows*2));
Mat gaussImg1;
GaussianBlur(dst1, gaussImg1, Size(3,3), 0);
threshold(gaussImg1, dst1, 200, 255,THRESH_BINARY);
vector<vector<Point> > conts;
vector<Vec4i> hierarchy;
findContours(dst1, conts, hierarchy, CV_RETR_TREE, CHAIN_APPROX_SIMPLE);
drawContours( img_1, conts, -1, Scalar(0,0,255), 2, LINE_AA, hierarchy, INT_MAX);
cout<< "轮廓数为:" <<conts.size()<<endl;
vector<Point2f> center_points;
int point_index = 1;
int max_radius = 0;
for (int i = 0; i < conts.size(); i++ ) {
RotatedRect box = minAreaRect(conts[i]);
Point2d center = box.center;
float width = box.size.width;
float height = box.size.height;
double area = round(box.size.area());
cout<<"第"<<i<<"个轮廓的中心点为:"<<center<<",它的长宽为:"<<width << "和" <<height <<"面积为:" <<area<<endl;
putText(img_1, to_string(point_index), center, FONT_HERSHEY_SIMPLEX, 0.6, Scalar(0, 0, 255));
point_index +=1;
}
imshow("final", img_1);
imwrite("final.png", img_1);
waitKey(0);
}
原始图片:
输出结果如下: