您的位置:首页 > 运维架构

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

2019-01-19 00:02 4355 查看

这段时间一直在用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();
}

相应的结果图:

膨胀图:

连通域检测图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: