這段時間一直在用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();
}
相應的結果圖:
膨脹圖:

連通域檢測圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。