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