服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - opencv提取外部轮廓并在外部加矩形框

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

2021-07-02 15:47修炼打怪的小乌龟 C/C++

这篇文章主要为大家详细介绍了opencv提取外部轮廓并在外部加矩形框,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

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

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

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

程序中具体的步骤为:

(1)灰度化、二值化

(2)图像膨胀

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

实现代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#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();
}

相应的结果图:

膨胀图:

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

连通域检测图:

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

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

原文链接:https://blog.csdn.net/u010417185/article/details/53101671?utm_source=blogxgwz13

延伸 · 阅读

精彩推荐