OpenCV邊緣檢測三種演算法(canny、sobel、laplacian)
阿新 • • 發佈:2018-11-21
Canny演算法
#include<opencv2\opencv.hpp> #include<opencv2\highgui\highgui.hpp> using namespace std; using namespace cv; //邊緣檢測 int main() { Mat img = imread("lol3.jpg"); imshow("原始圖", img); Mat DstPic, edge, grayImage; //建立與src同類型和同大小的矩陣 DstPic.create(img.size(), img.type()); //將原始圖轉化為灰度圖 cvtColor(img, grayImage, COLOR_BGR2GRAY); //先使用3*3核心來降噪 blur(grayImage, edge, Size(3, 3)); //執行canny運算元 Canny(edge, edge, 3, 9, 3); imshow("邊緣提取效果", edge); waitKey(0); }
Sobel演算法
#include<opencv2\opencv.hpp> #include<opencv2\highgui\highgui.hpp> using namespace std; using namespace cv; //邊緣檢測 int main() { Mat img = imread("lol3.jpg"); imshow("原始圖", img); Mat grad_x, grad_y; Mat abs_grad_x, abs_grad_y, dst; //求x方向梯度 Sobel(img, grad_x, CV_16S, 1, 0, 3, 1, 1,BORDER_DEFAULT); convertScaleAbs(grad_x, abs_grad_x); imshow("x方向soble", abs_grad_x); //求y方向梯度 Sobel(img, grad_y,CV_16S,0, 1,3, 1, 1, BORDER_DEFAULT); convertScaleAbs(grad_y,abs_grad_y); imshow("y向soble", abs_grad_y); //合併梯度 addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0, dst); imshow("整體方向soble", dst); waitKey(0); }
Laplacian演算法
#include<opencv2\opencv.hpp> #include<opencv2\highgui\highgui.hpp> using namespace std; using namespace cv; //邊緣檢測 int main() { Mat img = imread("lol3.jpg"); imshow("原始圖", img); Mat gray, dst,abs_dst; //高斯濾波消除噪聲 GaussianBlur(img, img, Size(3, 3), 0, 0, BORDER_DEFAULT); //轉換為灰度圖 cvtColor(img, gray, COLOR_RGB2GRAY); //使用Laplace函式 //第三個引數:目標影象深度;第四個引數:濾波器孔徑尺寸;第五個引數:比例因子;第六個引數:表示結果存入目標圖 Laplacian(gray, dst, CV_16S, 3, 1, 0, BORDER_DEFAULT); //計算絕對值,並將結果轉為8位 convertScaleAbs(dst, abs_dst); imshow("laplace效果圖", abs_dst); waitKey(0); }