opencv-015 自定義線性濾波
阿新 • • 發佈:2018-12-06
自定義線性濾波
l卷積概念
l常見運算元
l自定義卷積模糊
l程式碼演示
卷積概念
l卷積是影象處理中一個操作,是kernel在影象的每個畫素上的操作。
lKernel本質上一個固定大小的矩陣陣列,其中心點稱為錨點(anchor point)
卷積如何工作
l把kernel放到畫素陣列之上,求錨點周圍覆蓋的畫素乘積之和(包括錨點),用來替換錨點覆蓋下畫素點值稱為卷積處理。數學表達如下:
Sum = 8x1+6x1+6x1+2x1+8x1+6x1+2x1+2x1+8x1
New pixel = sum / (m*n)
常見運算元
Robert運算元
Sobel運算元
拉普拉斯運算元
自定義卷積模糊
lfilter2D方法filter2D(
Mat src, //輸入影象
Mat dst, // 模糊影象
int depth, // 影象深度32/8
Mat kernel, // 卷積核/模板
Point anchor, // 錨點位置
double delta // 計算出來的畫素+delta
)
其中 kernel是可以自定義的卷積核
#include <opencv2/opencv.hpp> #include <iostream> using namespace std; using namespace cv; Mat src, dst, gray_src; int main(int agrc, char** agrv) { src = imread("C:/Users/liyangxian/Desktop/bjl/nm3.jpg"); if (!src.data) { printf("no load..\n"); return -1; } const char* input_win = "input"; const char * out_put = "rober X"; namedWindow(input_win, CV_WINDOW_AUTOSIZE); namedWindow(out_put, CV_WINDOW_AUTOSIZE); imshow(input_win, src); //Robert X方向 Mat kernel_x = (Mat_<int>(2, 2) <<1, 0, 0, -1); filter2D(src, dst, -1, kernel_x, Point(-1, -1), 0.0); //Robert Y方向 Mat ying; Mat kernel_y = (Mat_<int>(2, 2) << 0, 1, -1, 0); filter2D(src, ying, -1, kernel_y, Point(-1, -1), 0.0); //sobel x方向 Mat sobx_pic; Mat sobel_x= (Mat_<int>(3, 3) << -1,0, 1, -2, 0,2,-1,0,1); filter2D(src, sobx_pic, -1, sobel_x, Point(-1, -1), 0.0); //sobel y方向 Mat soby_pic; Mat sobel_y = (Mat_<int>(3, 3) << -1, -2, -1, 0, 0, 0, 1, 2, 1); filter2D(src, soby_pic, -1, sobel_y, Point(-1, -1), 0.0); //拉普拉斯運算元 Mat lap_pic; Mat kernel_lap = (Mat_<int>(3, 3) << 0, -1, 0, -1, 4, -1, 0, -1, 0); filter2D(src, lap_pic, -1, kernel_lap, Point(-1, -1), 0.0); //自定義濾波,不斷重新整理進行模糊。 int c = 0; int index = 0; int ksize = 3; Mat dst_pic; while (true) { c = waitKey(500); if ((char)c == 27) {//ESC鍵 break; } ksize = 4 + (index % 5) * 2 + 1; Mat kernel = Mat::ones(Size(ksize, ksize), CV_32F) / (float)(ksize*ksize); filter2D(src, dst_pic, -1, kernel, Point(-1, -1)); index++; imshow("zidingyi", dst_pic); } imshow(out_put, dst); imshow("robert_y", ying); imshow("sobel_x", sobx_pic); imshow("sobel_y", soby_pic); imshow("lap_pic", lap_pic); waitKey(0); return 0; }