openCV处理图片

学习目标:

学习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);
}




原始图片:

f0f3746bccba4e2cace939d7053c0cef.png

 

输出结果如下:

86351fcac0ba42f395dc5efe7e84ddef.png


 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值