opencv提取外部轮廓并在外部加矩形框

这段时间一直在用opencv搞图像处理的问题,发现虽然可调用的函数多,但是直接找相应代码还是很困难,就行寻找连通域,并在连通域外侧加框,对于习惯使用Mat矩形操作的我,真心感觉代码少之又少,为防止以后自己还会用到,特在此记录一下。


要对下面的图像进行字符的边缘检测。




程序中具体的步骤为:

(1)灰度化、二值化

(2)图像膨胀

(3)检测膨胀图像的边缘并叫外矩形框


实现代码如下:

#include "stdafx.h"
#include "stdio.h"
#include "Base_process.h"
#include "opencv/cv.h"
#include "opencv/highgui.h"
#include <opencv2/opencv.hpp>
#include <tchar.h>
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;

void main()
{
    Mat src = imread("D:\\Recognize_Form_Project\\test_images\\0.jpg");//图片路径/*image180.jpg*/

	Mat gray_image;
	cvtColor(src, gray_image, CV_BGR2GRAY);
	imwrite("src.jpg", src);

	Mat binary_image;
	adaptiveThreshold(gray_image, binary_image, 255, CV_ADAPTIVE_THRESH_MEAN_C,
		CV_THRESH_BINARY_INV, 25, 10);  ///局部自适应二值化函数

	imwrite("erzhi.jpg", binary_image);

	//去噪
	Mat de_noise = binary_image.clone();
        //中值滤波
	
	medianBlur(binary_image, de_noise, 5);

	/   膨胀  
	Mat dilate_img;
	Mat element = getStructuringElement(MORPH_RECT, Size(20, 20/*15, 15*/));
	dilate(de_noise, dilate_img,element);
	imwrite("dilate.jpg", dilate_img);


	//外部加框
	//检测连通域,每一个连通域以一系列的点表示,FindContours方法只能得到第一个域
	vector<vector<Point>> contours;
	vector<Vec4i> hierarchy;
	findContours(dilate_img, contours, hierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);//CV_RETR_EXTERNAL只检测外部轮廓,可根据自身需求进行调整

	Mat contoursImage(dilate_img.rows, dilate_img.cols, CV_8U, Scalar(255));
	int index = 0;
	for (; index >= 0; index = hierarchy[index][0]) {
		cv::Scalar color(rand() & 255, rand() & 255, rand() & 255);
		// for opencv 2
		// cv::drawContours(dstImage, contours, index, color,  CV_FILLED, 8, hierarchy);//CV_FILLED所在位置表示轮廓线条粗细度,如果为负值(如thickness==cv_filled),绘制在轮廓内部
		// for opencv 3
		//cv::drawContours(contoursImage, contours, index, color, cv::FILLED, 8, hierarchy);

		cv::drawContours(contoursImage, contours, index, Scalar(0), 1, 8, hierarchy);//描绘字符的外轮廓

		Rect rect = boundingRect(contours[index]);//检测外轮廓
		rectangle(contoursImage, rect, Scalar(0,0,255), 3);//对外轮廓加矩形框
	}


	imwrite("zt.jpg", contoursImage);

	cout << "完成检测";

	de_noise.release();
	element.release();
	dilate_img.release();
	binary_image.release();
	gray_image.release();
}

相应的结果图:

膨胀图:


连通域检测图:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值