前言
上篇基礎篇已經實現opencv環境開發的配置以及圖像加載和顯示,下面這篇是基於圖像邊緣檢測實踐,這裏同樣使用C++語言,其實我個人更擅長python,使用python實現會更加簡潔,話不多說了,直接上代碼。。。
opencv實現邊緣檢測demo
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
String imageName("1.png"); // 圖片路徑
Mat src,src_blur, src_gray;
src = imread(imageName); // 讀取文件
if (src.empty()) {
return -1;
}
imshow("原圖", src);
GaussianBlur(src, src_blur,Size(15,15),0);//高斯濾波,降噪
cvtColor(src_blur, src_gray, COLOR_BGR2GRAY);//圖像轉換爲灰度
Mat bw;
adaptiveThreshold(~src_gray, bw, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 15, -2);
//imshow("bw", bw);
Mat horizontal = bw.clone();
Mat vertical = bw.clone();
//在水平軸上指定大小
int horizontalsize = horizontal.cols / 30;
//創建結構元素,用於通過形態運算提取水平線
Mat horizontalStructure = getStructuringElement(MORPH_RECT, Size(horizontalsize, 1));
erode(horizontal, horizontal, horizontalStructure, Point(-1, -1));
dilate(horizontal, horizontal, horizontalStructure, Point(-1, -1));
imshow("horizontal", horizontal);
//在垂直軸上指定大小
int verticalsize = vertical.rows / 30;
Mat verticalStructure = getStructuringElement(MORPH_RECT, Size(1, verticalsize));
erode(vertical, vertical, verticalStructure, Point(-1, -1));
dilate(vertical, vertical, verticalStructure, Point(-1, -1));
imshow("vertical",vertical);
//獲取反向垂直圖像
bitwise_not(vertical, vertical);
//imshow("vertical_bit",vertical);
//根據邏輯提取邊緣和平滑圖像處理
// Step 1 提取邊緣
Mat edges;
adaptiveThreshold(bw, edges, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 3, -2);
imshow("edges", edges);
// Step 2 擴張
Mat kernel = Mat::ones(3, 3, CV_8UC1);
dilate(edges, edges, kernel);
//imshow("dilate", edges);
// Step 3 模糊
Mat smooth;
vertical.copyTo(smooth);
// Step 4 模糊平滑圖片
blur(smooth, smooth, Size(5, 5));
smooth.copyTo(vertical, edges);
//imshow("smooth", vertical);
waitKey(0);
return 0;
}
程序運行效果如下:
檢測識別效果還算可以,還有待改進,使用OpenCV函數 Canny來實現的話效果更好一些。