首页 > 代码库 > OpenCV Tutorials —— Making your own linear filters
OpenCV Tutorials —— Making your own linear filters
kernel
A kernel is essentially a fixed size array of numerical coefficeints along with an anchor point in that array, which is tipically located at the center.
The value of the convolution is calculated in the following way:
- 1,Place the kernel anchor on top of a determined pixel, with the rest of the kernel overlaying the corresponding local pixels in the image.
2,Multiply the kernel coefficients by the corresponding image pixel values and sum the result.
- 3,Place the result to the location of the anchor in the input image.
4,Repeat the process for all pixels by scanning the kernel over the entire image.
Expressing the procedure above in the form of an equation we would have:
Fortunately, OpenCV provides you with the function filter2D so you do not have to code all these operations.
kernel_size = 3 + 2*( ind%5 );kernel = Mat::ones( kernel_size, kernel_size, CV_32F )/ (float)(kernel_size*kernel_size);
The first line is to update the kernel_size to odd values in the range: . The second line actually builds the kernel by setting its value to a matrix filled with and normalizing it by dividing it between the number of elements.
filter2D(src, dst, ddepth , kernel, anchor, delta, BORDER_DEFAULT );
src: Source imagedst: Destination image ddepth: The depth of dst. A negative value (such as ) indicates that the depth is the same as the source. kernel: The kernel to be scanned through the image anchor: The position of the anchor relative to its kernel. The location Point(-1, -1) indicates the center by default. delta: A value to be added to each pixel during the convolution. By default it is BORDER_DEFAULT: We let this value by default (more details in the following tutorial)
Code
#include "stdafx.h"#include "opencv2/imgproc/imgproc.hpp"#include "opencv2/highgui/highgui.hpp"#include <stdlib.h>#include <stdio.h>using namespace cv;/** @function main */int main ( int argc, char** argv ){ /// Declare variables Mat src, dst; Mat kernel; Point anchor; double delta; int ddepth; int kernel_size; char* window_name = "filter2D Demo"; int c; /// Load an image src = http://www.mamicode.com/imread("img2.jpg" ); if( !src.data ) { return -1; } /// Create window namedWindow( window_name, CV_WINDOW_AUTOSIZE ); /// Initialize arguments for the filter anchor = Point( -1, -1 ); delta = 0; ddepth = -1; /// Loop - Will filter the image with different kernel sizes each 0.5 seconds int ind = 0; while( true ) { c = waitKey(500); /// Press ‘ESC‘ to exit the program if( (char)c == 27 ) { break; } /// Update kernel size for a normalized box filter kernel_size = 3 + 2*( ind%5 ); kernel = Mat::ones( kernel_size, kernel_size, CV_32F )/ (float)(kernel_size*kernel_size); /// Apply filter filter2D(src, dst, ddepth , kernel, anchor, delta, BORDER_DEFAULT ); imshow( window_name, dst ); ind++; } return 0;}
OpenCV Tutorials —— Making your own linear filters