当前位置:网站首页>[opencv] - linear filtering: box filtering, mean filtering, Gaussian filtering
[opencv] - linear filtering: box filtering, mean filtering, Gaussian filtering
2022-06-28 23:22:00 【I love to learn】
List of articles
- One 、 Linear filtering : Box filtering 、 Mean filtering 、 Gauss filtering
- 1、 Smoothing
- 2、 Image filtering and filter
- 3、 Introduction to linear filter
- 4、 Filtering and blurring
- 5、 Neighborhood operator and linear domain filtering
- 6、 Box filtering (box Filter)
- 7、 Mean filtering
- 8、 Gauss filtering
- 9、 Linear filter correlation OpenCV The source code parsing
- 10、OpenCV in GaussianBlur Function source code analysis
- 11、 Image linear filtering synthesis example
One 、 Linear filtering : Box filtering 、 Mean filtering 、 Gauss filtering
1、 Smoothing
Smoothing (smoothing) Also known as fuzzy processing (bluring), It is a simple and frequently used image processing method . Smoothing has many uses , The most common is to reduce noise or distortion on the image . When processing reduced image resolution , Smoothing is an easy way to use .
2、 Image filtering and filter
(1) Image noise : It refers to unnecessary or redundant interference information stored in image data . The existence of noise seriously affects the quality of remote sensing images , Therefore, before image enhancement processing and classification processing , Must be corrected .[1] All kinds of factors in the image that hinder people from accepting their information can be called image noise . In theory, noise can be defined as “ unpredictable , Random errors that can only be recognized by means of probability and statistics ”.
(2) Image filtering : It refers to suppressing the noise of the target image while preserving the detailed features of the image as much as possible , It is an indispensable operation in image preprocessing , The quality of its processing effect will directly affect the effectiveness and reliability of subsequent image processing and analysis .
Eliminating noise components in an image is called image smoothing or filtering . Most of the energy of the signal or image is concentrated in the low and medium frequency band of the amplitude spectrum , In the higher frequency band , Useful information is often overwhelmed by noise .
(3) There are two purposes of image filtering :
- Extract the feature of the object as the feature pattern of image recognition ;
- To meet the requirements of image processing , Eliminate the noise in image digitization .
There are also two requirements for filtering :
- It is not allowed to damage important information such as the outline and edge of the image ;
- Make the image clear and have a good visual angle .
(4) Smooth filtering : Low frequency enhanced spatial domain filtering technology . There are two kinds of purposes : One is fuzzy ; The other is to eliminate noise ;
The smoothing filtering in spatial domain is usually carried out by simple average method , Is to find the adjacent pixel points ( Pixel point ) Average brightness value of . The size of the neighborhood is directly related to the smoothing effect , The larger the neighborhood, the better the smoothing effect , But the neighborhood is too big , Smoothing will also make the loss of edge information greater , So that the output image becomes blurred , Therefore, it is necessary to choose the size of neighborhood reasonably .
(5) filter :
About filters , A figurative metaphor is : Think of the filter as a window with weighting coefficients , When using this filter to smooth the image , Just put this window on the image , Let's look at the image we got through this window .
There are many kinds of filters , Are encapsulated in separate functions :
- Box filtering ——BoxBlur function
- Mean filtering —— Also called neighborhood average filtering ——Blur function
- Gauss filtering ——GaussianBlur function
- median filtering ——medianBlur function
- Bilateral filtering ——bilateralFilter function
3、 Introduction to linear filter
explain : Linear filters are often used to eliminate unwanted frequencies from an input signal or to select a desired frequency from many frequencies .
- low pass filter : Allow low frequencies to pass through
- High pass filter : Allow high frequency passage
- Bandpass filter : Allow a certain range of frequencies to pass
- Band stop filter : Prevent a certain range of frequencies from passing and allow other frequencies to pass
- All pass filter : Allow all frequencies to pass through , Just change the phase relationship
- Notch filter (Band-Stop Filter): Prevent a narrow frequency range from passing through , It is a special band stop filter
4、 Filtering and blurring
Take Gaussian filtering as an example : Filtering can be divided into low-pass filtering and high pass filtering : Gaussian filtering refers to the filtering operation using Gaussian function as the filtering function , As for whether it's fuzzy , It depends on Gauss low pass or Gauss high pass , Low pass is fuzzy , Qualcomm is sharpening .
5、 Neighborhood operator and linear domain filtering
Neighborhood operators ( Local operators ) Is the use of a given pixel around the value of the pixel to determine the final output value of this pixel . Linear neighborhood filtering is a common neighborhood operator , The output value of a pixel depends on the weighted sum of the input pixels , As follows :
Add :
Image smoothing : Refers to a wide area used to highlight the image 、 Low frequency components 、 Trunk part or suppression Image noise And interference with high-frequency components , Make the brightness of the image smooth and gradual , Reduce the mutation gradient , Image processing method for improving image quality .
Sharpen the image : It means to compensate the contour of the image , Enhance the edge of the image and the gray jump part , Make the image clear , It can be divided into spatial domain processing and frequency domain processing . Image sharpening is to highlight the edge of the figure on the image 、 outline , Or the characteristics of some linear objective elements .
The neighborhood operator is not only used for local tone adjustment , It can also be used for image filtering , To smooth and sharpen the image , Image edge enhancement or image noise removal .
Linear neighborhood filter operator : That is, use different weights to combine pixels in a small neighborhood , To get the treatment effect :

Figure note : Neighborhood filtering ( Convolution )—— The convolution of the left image and the middle image produces the right image . The blue marked pixels in the target image are calculated by using the red marked pixels in the original image .
The output pixel value of the linear filtering process g(i,j) Is the input pixel value f(i+k,j+I) Weighted sum of , Among them h(k,l) We call it ” nucleus ", Is the weighting coefficient of the filter , That is, the filter ” Filter coefficient “. as follows :
Abbreviation :f Enter pixel values for ,h Which represents the weighting coefficient ” nucleus “,g Represents the output pixel value

6、 Box filtering (box Filter)
explain : The block filter is encapsulated in a file named boxblur The function of , namely boxblur The function uses a block filter (box
filter) To blur a picture , from src Input , from dst Output .
void boxFileter(InputArray src,OutputArray dst,int ddepth,Size ksize,Point
anchor=Point(-1,-1),boolnormalize=true,int borderType=BORDER_DEFAULT)
The first parameter : The input image , Source image , fill Mat Class . This function is independent of the channel , And can process any number of channels of the picture . However, it should be noted that the depth of the image to be processed should be CV_8U,CV_16U,CV_16S,CV_32F, as well as CV_64F One of .
Add : Pixel depth And image depth are two interrelated but different concepts . Pixel depth refers to the number of bits required to store each pixel . Assume that storing each pixel requires 8bit, Then the pixel depth of the image is 8. Image depth refers to the number of bits in the pixel depth that are actually used to store the gray or color of the image . Assume that the pixel depth of the image is 16bit, But the number of bits used to represent the gray or color of the image is only 15 position , Then the image depth of the image is 15. The number of pixels determines the possible depth of each image , Or possible grayscale levels . for example , Each pixel of the color image is marked with R,G,B Three components represent , Use... For each component 8 position , Pixel depth is 24 position .
The second parameter : Target image , Need the same size and type as the source image
The third parameter : The depth of the output image ,-1 Represents using the original image depth , namely src.depth()
Fourth parameter : The size of the kernel . commonly Size(w,h) To represent the size of the kernel , among w For pixel width ,h Indicates the pixel height .Size(3x3) Express 3x3 The nuclear size of ,Size(5,5) Express 5x5 Nuclear size
Fifth parameter : Represents an anchor ( The point that is smoothed ). Be careful : It has a default value Point(-1,-1). If the coordinates of this point are negative , It means that the center of the core is the anchor point , So the default value is Point(-1,-1) It means that the anchor is in the center of the core
Sixth parameter : The default value is true, An identifier , Indicates whether the kernel is normalized by other regions (normalized) 了
Seventh parameter : An edge pattern used to infer pixels outside the image . Have default values BORDER_DEFAULT, Generally, it does not need to be considered
BoxFileter() The kernel used for functional block filtering is represented as follows :

In the above formula f Show the original picture ,h Representation core ,g Represents the target graph , When normalize=true When , So we're familiar with the mean of filtering . in other words , Mean filtering is a box filter normalization (normalized) After the special situation . among , Normalization is to scale the amount to be processed to a range , such as (0,1), In order to deal with the nuclear visual quantification in a unified way . Not normalized (Unnormalized) The block filter of is used to calculate the integral characteristics in the neighborhood of each pixel , Such as dense optical flow algorithm (dense optical flow algorithms) The covariance matrix of the reciprocal of the image used in (covariance matrices of image derivatives)
An example of the calling code is as follows :
Mat image=imread("2.jpg");
// Perform mean filtering operation
Mat out;
boxFilter(image,out,-1,Size(5,5));
The sample program : Use box filtering to blur a picture
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
int main()
{
// Load the image
Mat image = imread("E:\\dong.jpg");
namedWindow(" Box filtering 【 Original picture 】");
namedWindow(" Box filtering 【 design sketch 】");
// Show the original
imshow(" Box filtering 【 Original picture 】", image);
// Perform the filtering operation
Mat out;
boxFilter(image, out, -1, Size(5, 5));
// Show renderings
imshow(" Box filtering 【 design sketch 】", out);
waitKey(0);
}

7、 Mean filtering
explain : Mean filtering , It's the simplest filtering operation , Each pixel of the output image is the average value of the corresponding pixel of the input image in the core window ( All pixels are weighted equally ), Among them, it is the normalized block filter .
7.1 Theoretical analysis of mean filtering
Mean filtering is a typical linear filtering algorithm , The main method is neighborhood average method , That is to use the average value of each pixel in an image area to replace the value of each pixel in the original image . It is generally necessary to give a template to the target pixel on the image ( kernel ), The template includes neighboring pixels around it ( For example, around the target pixel 8(3x3-1) Pixel , Form a filter template , That is, remove the target pixel itself ). Then the average value of all pixels in the template is used to replace the original pixel value . The current pixel to be processed (x,y), Select a template , The template is composed of several adjacent pixels , Find the mean value of all pixels in the template , Then assign the mean value to the current pixel (x,y), As the gray point of the processed image at this point g(x,y), namely g(x,y)=1/m Sum up f(x,y), among m Is the total number of pixels in the template including the current pixel .
7.2 The defect of mean filtering
There are inherent defects in mean filtering itself , That is, it can't protect image details very well , In the process of image denoising, it also destroys the details of the image , So that the image becomes blurred , Can't get rid of noise well .
7.3 stay OpenCV Mean filtering is used in ——blur function
blur Function function : For the input image src After mean filtering, use dst Output
blur Function in OpenCV In official documents , The given kernel is like this :

This kernel is easy to see , Is to find the average , namely blur The function encapsulates the mean filter . The function prototype is as follows :
void blur(InputArray src,OutputArray dst,Size kize,Point anchor=Point(-1,-1),
int borderType=BORDER_DEFAULT)
- The first parameter : The input image , Source image , fill Mat Class . This function is independent of the channel , And can process any number of channels of the picture . However, it should be noted that the depth of the image to be processed should be CV_8U,CV_16U,CV_16S,CV_32F, as well as CV_64F One of .
- The second parameter : Target image , Need the same size and type as the source image . For example, you can use Mat::Clone, Take the source image as the template , To initialize the target graph such as the fake packet exchange .
- The third parameter : The size of the kernel . commonly Size(w,h) To represent the size of the kernel , among w For pixel width ,h Indicates the pixel height .Size(3x3) Express 3x3 The nuclear size of ,Size(5,5) Express 5x5 Nuclear size
- Fourth parameter : Represents an anchor ( The point that is smoothed ). Be careful : It has a default value Point(-1,-1). If the coordinates of this point are negative , It means that the center of the core is the anchor point , So the default value is Point(-1,-1) It means that the anchor is in the center of the core .
- Fifth parameter : An edge pattern used to infer pixels outside the image . Have default values BORDER_DEFAULT, Generally, it does not need to be considered .
An example of the calling code is as follows :
Mat image=imread("1.jpg");
Mat out;
blur(image,out,Size(7,7));
The sample program : Use Blur Mean filtering
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
int main()
{
// Load the image
Mat image = imread("E:\\tangsan.jpg");
namedWindow(" Mean filtering 【 Original picture 】");
namedWindow(" Mean filtering 【 design sketch 】");
// Show the original
imshow(" Mean filtering 【 Original picture 】", image);
// Perform the filtering operation
Mat out;
blur(image, out, Size(7, 7));
// Show renderings
imshow(" Mean filtering 【 design sketch 】", out);
waitKey(0);
}

8、 Gauss filtering
8.1 A brief analysis of the theory of Gaussian filtering
Gauss filter is a linear smoothing filter , Can eliminate Gaussian noise , Noise reduction process widely used in image processing . Generally speaking , Gaussian filtering is the process of weighted average of the whole image , Value of each pixel , Are obtained by averaging itself and other pixel values in the neighborhood . The specific operation of Gaussian filtering is : Use a template ( Convolution 、 A mask ) Scan every pixel in the image , Using the weighted average gray value of the pixels in the neighborhood determined by the template to replace the value of the central pixel of the template .
Gaussian filtering is the most useful filtering operation , Although it is often not the most efficient . Image generated by Gaussian blur Technology , Its visual effect is like looking at an image through a translucent screen , This is obviously different from the effect of out of focus imaging and the effect of general lighting shadow . Gaussian smoothing is used in the preprocessing stage of computer vision algorithm , In order to enhance the image effect in different scale size ( Participate in scale space representation and scale space implementation ). Gaussian blur : Gaussian blur process of image is convolution of image and normal distribution , Normal distribution is also called Gaussian distribution .
Convolution of the image with the circular box blur will produce a more accurate out of focus imaging effect . Because the Fourier transform of Gaussian function is another Gaussian function , So Gaussian blur is a low-pass filtering operation for image processing .
Gaussian filter is a kind of linear smoothing filter which selects the weight according to the shape of Gaussian function . Gaussian smoothing filter is very effective to suppress noise which obeys normal distribution . The one-dimensional zero mean Gaussian function is as follows :

among Sigma Determines the width of the Gaussian function . For image processing , Commonly used two-dimensional zero mean discrete Gaussian function as smoothing filter .
The two-dimensional Gaussian function is as follows :

8.2 Gauss filtering :GaussianBlur function
explain :GaussianBlur The function blurs an image with a Gaussian filter , For the input image src After Gaussian filtering, use dst Output . It convolutes the source image with the specified Gaussian kernel function , And support local filtering (In-placefiltering)
void GaussianBlur(InputArray src,OutArray dst,Size ksize,double sigmaX,double sigmaY=0,
intborderType=BORDER_DEFAULT)
- The first parameter : The input image , Source image , fill Mat Class . This function is independent of the channel , And can process any number of channels of the picture . However, it should be noted that the depth of the image to be processed should be CV_8U,CV_16U,CV_16S,CV_32F, as well as CV_64F One of .
- The second parameter : Target image , Need the same size and type as the source image . For example, you can use Mat::Clone, Take the source image as the template , To initialize the target graph such as the fake packet exchange .
- The third parameter : The size of the kernel . among ksize.width and ksize.height Can be different , But they must both be positive and odd , Or zero , It's all about sigma Calculated .
- Fourth parameter : Denotes that the Gaussian kernel function is in X Standard deviation of direction
- Fifth parameter : Denotes that the Gaussian kernel function is in Y Standard deviation of direction . if sigmaY by 0, Set it to sigmaX; If sigmaX and sigmaY All are 0, By ksize.width and ksize.height Calculation
- Sixth parameter : Some kind of boundary pattern used to infer pixels outside the image . Have default values BORDER_DEFAULT
An example of the call is as follows :
Mat image=imread("1.jpg");
Mat out;
GaussianBlur(image,out,Size(5,5),0,0);
GaussianBlur Function complete sample program :
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
int main()
{
// Load the image
Mat image = imread("E:\\tangsan.jpg");
namedWindow(" Gauss filtering 【 Original picture 】");
namedWindow(" Gauss filtering 【 design sketch 】");
// Show the original
imshow(" Gauss filtering 【 Original picture 】", image);
// Perform the filtering operation
Mat out;
GaussianBlur(image, out, Size(3, 3), 0, 0);
// Show renderings
imshow(" Gauss filtering 【 design sketch 】", out);
waitKey(0);
}

9、 Linear filter correlation OpenCV The source code parsing
9.1OpenCV in boxFilter Function source code analysis
boxFilter The source code of the function is as follows :
void cv::boxFilter(InputArray _src, OutputArray _dst, int ddepth,
Size ksize, Point anchor,
bool normalize, int borderType)
{
Mat src = _src.getMat();// Copy the formal parameters of the source graph Mat Data to temporary variable ,
int sdepth=src.depth(),cn=src.channels();// Definition int Temporary variable , Represents the depth of the source image sdepth, Reference of source graph channel cn
// Handle ddepth Less than 0 The situation of
if (ddepth < 0)
ddepth = sdepth;
_dst.create(src.size(), CV_MAKETYPE(ddepth, cn));// Initialize the target graph
Mat dst = _dst.getMat();// Copy the formal parameters of the target graph Mat Data to temporary variable , For later operations
// Handle borderType Not for BORDER_CONSTANT And normalize For the truth
if (borderType != BORDER_CONSTANT && normaliz)
{
if (src.rows == 1)
ksize.height = 1;
if (src.cols == 1)
ksize.width = 1;
}
// If you've ever had HAVE_TEGRA_OPTIMIZATION Definition of optimization options , Execute... In the macro body tegra Optimize the function and return
#define HAVE_TEGRA_OPTIMIZATION
if(tegra::box(src,dst,ksize,anchor,normalize,borderType))
return;
#endif
// call FilteEngine Filter engine , Officially start the filtering operation
Ptr<FilterEngine> f = createBoxFilter(src.type(), dst.type(),
ksize, anchor, normalize, borderType);
f->apply(src, dst, wsz, ofs);
}
Above ,Ptr Is a smart pointer template class for dynamically allocated objects . You can find , The internal code of the function is very clear : First copy the formal parameters of the source image Mat Data to temporary variable , Define some temporary variables , To deal with ddepth Less than zero , And then deal with borderType Not for BORDER_CONSTANT And normalize For the truth , The final call FileEngine The filter engine creates a BoxFilter, Formal filtering operation .
9.2 FilterEngine Class parsing :OpenCV Image filtering core engine
explain :FilterEngine Class is OpenCV On the main force of image filtering , yes OpenCV The core engine of image filtering function . Various filter functions such as blur、GaussianBlur, In fact, it is to define a at the end of the function Ptr Type of f, then f->apply(src,dst).
This class can apply almost all filtering operations to images , It contains all the necessary intermediate buffers . There are many filter related create The return value of the coefficient function is directly Ptr, Such as :
cv::createSeparableLinearFiter()
cv::createLinearFilter(),cv::createGaussianFilter(),cv::createDerivFilter()
cv::createBoxFilter()
cv::createMorphologyFileter()
Here is a prototype of one of the functions :
Ptr<FilterEngine>createLinearFilter(int srcType,int dstType,InputArray kernel,Point_anchor=Point(-1,-1),
double delta=0,int rowBorderType=BORDER_DEFAULT,intcolumBorderType=-1,const Scalar& borderValue=Saclar())
Ptr Is a smart pointer template class for dynamically allocated objects , The template parameter in angle brackets is FilterEngine:
Use FilterEngine Class can process a large number of images in blocks , Make up a complex pipeline , It includes some filtering stages . If a pre-defined filtering operation is used , Yes cv::filter2D()、cv::erode() and cv::dilate() You can choose , They don't depend on FilterEngine, It is implemented inside its own function body FilterEngine Features provided ; Unlike other things like blur Series of functions , Depend on and depend on FilterEngine engine .
Next, let's look at the annotated source code of its class declaration , as follows :
//-----------------------------------【FilterEngine Class Chinese annotated version source code 】----------------
// Source path :…\opencv\sources\modules\imgproc\include\opencv2\imgproc\imgproc.hpp
// The number of starting lines of the following code in the source file :222 That's ok
// Chinese annotation by Light ink
//-----------------------------------------------------------------------------------
class CV_EXPORTS FilterEngine
{
public:
// Default constructor
FilterEngine();
// Complete constructor . _filter2D 、_rowFilter and _columnFilter One of , Must be non empty
FilterEngine(const Ptr<BaseFilter>& _filter2D,
constPtr<BaseRowFilter>& _rowFilter,
constPtr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, intbufType,
int_rowBorderType=BORDER_REPLICATE,
int _columnBorderType=-1,
const Scalar&_borderValue=Scalar());
// Default destructor
virtual ~FilterEngine();
// Reinitialize the engine . Release the memory requested by the previous filter .
void init(const Ptr<BaseFilter>& _filter2D,
constPtr<BaseRowFilter>& _rowFilter,
constPtr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, intbufType,
int_rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
const Scalar&_borderValue=Scalar());
// Start specifying ROI Area and size of the image for filtering operation
virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
// Start specifying ROI The image of the region is filtered
virtual int start(const Mat& src, const Rect&srcRoi=Rect(0,0,-1,-1),
bool isolated=false, intmaxBufRows=-1);
// The next step in processing the image srcCount That's ok ( The third argument to the function )
virtual int proceed(const uchar* src, int srcStep, int srcCount,
uchar* dst, intdstStep);
// The specified for the image ROI Filter the area , if srcRoi=(0,0,-1,-1), Then filter the whole image
virtual void apply( const Mat& src, Mat& dst,
const Rect&srcRoi=Rect(0,0,-1,-1),
Point dstOfs=Point(0,0),
bool isolated=false);
// If the filter is separable , Then return to true
boolisSeparable() const {
return (const BaseFilter*)filter2D == 0; }
// Returns the number of input and output lines
int remainingInputRows() const;
intremainingOutputRows() const;
// Some member parameter definitions
int srcType, dstType, bufType;
Size ksize;
Point anchor;
int maxWidth;
Size wholeSize;
Rect roi;
int dx1, dx2;
int rowBorderType, columnBorderType;
vector<int> borderTab;
int borderElemSize;
vector<uchar> ringBuf;
vector<uchar> srcRow;
vector<uchar> constBorderValue;
vector<uchar> constBorderRow;
int bufStep, startY, startY0, endY, rowCount, dstY;
vector<uchar*> rows;
Ptr<BaseFilter> filter2D;
Ptr<BaseRowFilter> rowFilter;
Ptr<BaseColumnFilter> columnFilter;
};
9.3 OpenCV in blur Function source code analysis
explain :blur A function is called internally boxFilter function , And the first 6 The parameter is true, That is, as mentioned above normalize=true, That is, the mean filter is the box filter after homogenization .
void cv::blur(InputArray src,OutputArray dst,Size ksize,Point anchor,int borderType)
{
// call boxFilter Function to process
boxFilter(src,dst,-1,ksize,anchor,true,borderType);
}
10、OpenCV in GaussianBlur Function source code analysis
void cv::GaussianBlur( InputArray _src, OutputArray _dst, Size ksize,
double sigma1, double sigma2,
int borderType )
{
// Initialization and boundary type judgment
CV_INSTRUMENT_REGION()
int type = _src.type();
Size size = _src.size();
_dst.create( size, type );
if( borderType != BORDER_CONSTANT && (borderType & BORDER_ISOLATED) != 0 )
{
if( size.height == 1 )
ksize.height = 1;
if( size.width == 1 )
ksize.width = 1;
}
// Easy to understand , If the size of Gaussian filter is 1, According to the Gaussian function, the coefficient is 1, So you copy the input to the output
if( ksize.width == 1 && ksize.height == 1 )
{
_src.copyTo(_dst);
return;
}
//OpenCV For some ksize = 3 and 5 The situation has been done OpenCL Optimize , So initialization OpenCL Correlation function
bool useOpenCL = (ocl::isOpenCLActivated() && _dst.isUMat() && _src.dims() <= 2 &&
((ksize.width == 3 && ksize.height == 3) ||
(ksize.width == 5 && ksize.height == 5)) &&
_src.rows() > ksize.height && _src.cols() > ksize.width);
(void)useOpenCL;
int sdepth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type);
// obtain gaussianKernels
Mat kx, ky;
createGaussianKernels(kx, ky, type, ksize, sigma1, sigma2);
// call opencl Calculate
CV_OCL_RUN(useOpenCL, ocl_GaussianBlur_8UC1(_src, _dst, ksize, CV_MAT_DEPTH(type), kx, ky, borderType));
// If not ksize=3 perhaps 5 The situation of , Consider using filter2D Of opencl Optimization program calculation
CV_OCL_RUN(_dst.isUMat() && _src.dims() <= 2 && (size_t)_src.rows() > kx.total() && (size_t)_src.cols() > kx.total(),
ocl_sepFilter2D(_src, _dst, sdepth, kx, ky, Point(-1, -1), 0, borderType))
// If OpenCL Version of filter2D Still can't calculate , select cpu Version of gaussianBlur
Mat src = _src.getMat();
Mat dst = _dst.getMat();
Point ofs;
Size wsz(src.cols, src.rows);
if(!(borderType & BORDER_ISOLATED))
src.locateROI( wsz, ofs );
CALL_HAL(gaussianBlur, cv_hal_gaussianBlur, src.ptr(), src.step, dst.ptr(), dst.step, src.cols, src.rows, sdepth, cn,
ofs.x, ofs.y, wsz.width - src.cols - ofs.x, wsz.height - src.rows - ofs.y, ksize.width, ksize.height,
sigma1, sigma2, borderType&~BORDER_ISOLATED);
CV_OVX_RUN(true,
openvx_gaussianBlur(src, dst, ksize, sigma1, sigma2, borderType))
CV_IPP_RUN_FAST(ipp_GaussianBlur(src, dst, ksize, sigma1, sigma2, borderType));
// if CPU Version of gaussianBlur Still can't calculate , select CPU Version of filter2D
sepFilter2D(src, dst, sdepth, kx, ky, Point(-1, -1), 0, borderType);
}
11、 Image linear filtering synthesis example
Add : In computer vision “ kernel ” It is a box used to circle the surrounding pixels used to calculate the new value of a pixel ( round , Or any shape ).
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<iostream>
using namespace cv;
using namespace std;
//---------------------------------
// Global variable declaration
//-------------------------------
Mat g_srcIamge, g_dstImage1, g_dstImage2, g_dstImage3;// Store pictures Mat type
int g_nBoxFilterValue = 3;// Block filter parameter value
int g_nMeanBlurValue = 3;// Mean filter parameter value
int g_nGaussianBlurValue = 3;// Gaussian filter parameter value
//---------------------------------
// Global function declaration
//-------------------------------
static void on_BoxFilter(int, void *);// Box filtering
static void on_MeanBlur(int, void *);// Mean filtering
static void on_GaussianBlur(int, void *);// Gauss filtering
int main()
{
// change console The font color
system("color 5E");
// Load original
g_srcIamge = imread("E:\\tangsan.jpg", 1);
if (!g_srcIamge.data)
{
printf(" Error reading picture \n");
return false;
}
// Copy the original image to three Mat Type in the
g_dstImage1 = g_srcIamge.clone();
g_dstImage2 = g_srcIamge.clone();
g_dstImage3 = g_srcIamge.clone();
// Show the original
namedWindow("【<0> Original window 】", 1);
imshow("【<0> Original window 】", g_srcIamge);
//=========1、 Box filtering ===========
// create a window
namedWindow("【<1> Box filtering 】",1);
// Create a trackbar
createTrackbar(" Kernel value :", "【<1> Box filtering 】", &g_nBoxFilterValue, 40, on_BoxFilter);
on_MeanBlur(g_nBoxFilterValue, 0);
//======2、 Mean filtering ===========
namedWindow("【<2> Mean filtering 】", 1);
// Create a trackbar
createTrackbar(" Kernel value :", "【<2> Mean filtering 】", &g_nMeanBlurValue, 40, on_BoxFilter);
on_MeanBlur(g_nMeanBlurValue, 0);
//=====3、 Gauss filtering ===============
namedWindow("【<3> Gauss filtering 】", 1);
// Create a trackbar
createTrackbar(" Kernel value :", "【<3> Gauss filtering 】", &g_nGaussianBlurValue, 40, on_BoxFilter);
on_GaussianBlur(g_nGaussianBlurValue, 0);
// Output some help information
cout << endl << " Please adjust the scroll bar to observe the image effect ~\n\n" << "\t Press down “q” Key time , Program exit ~\n";
// stay waitKey(1) Then enter a value
while(char(waitKey(1)!='q')){
}
return 0;
}
//----------------------
// Callback function of block filter operation
//---------------------------
static void on_BoxFilter(int, void *)// Box filtering
{
boxFilter(g_srcIamge, g_dstImage1, -1, Size(g_nBoxFilterValue + 1, g_nBoxFilterValue + 1));
imshow("【<1> Box filtering 】", g_dstImage1);
}
static void on_MeanBlur(int, void *)// Mean filtering
{
blur(g_srcIamge, g_dstImage2, Size(g_nMeanBlurValue + 1, g_nMeanBlurValue + 1), Point(-1, -1));
imshow("【<2> Mean filtering 】", g_dstImage2);
}
static void on_GaussianBlur(int, void *)// Gauss filtering
{
GaussianBlur(g_srcIamge, g_dstImage3,
Size(g_nGaussianBlurValue * 2 + 1, g_nGaussianBlurValue * 2 + 1), 0, 0);
imshow("【<3> Gauss filtering 】", g_dstImage3);
}
Sample screenshot :
(1) Original image 
(2) Box filtering 
(3) Mean filtering 
(4) Gauss filtering 
边栏推荐
- Would like to ask, how to open a stock account? Is it safe to open an account online?
- MSCI 2022 market classification assessment
- Insomnia last night
- [chapter 71 of the flutter problem series] mutual conversion between uint8list and image in flutter
- Tanghongbin, Yaya live CTO: to truly localize, the product should not have the attribute of "origin"
- Undefined symbol main (referred from entry9a.o).
- 一张能卖上千万,商家扩张比玩家还快:球星卡的江湖你不懂
- Flutter obtains the coordinate size of any element in the interface through globalkey
- Is it safe to open a stock account on the Internet?
- 大三,不简单啊!
猜你喜欢
![[mathematical modeling] fmincon() function of MATLAB nonlinear programming](/img/fc/46949679859b1369fcc83d0d8b637c.png)
[mathematical modeling] fmincon() function of MATLAB nonlinear programming

YuMinHong set up two funds funded by his hometown

Hit the industry directly | the flying propeller launched the industry's first model selection tool

第五章 虚拟存储器 练习

2022年PMP项目管理考试敏捷知识点(4)

机器学习4-降维技术

C interview questions_ 20220627 record

【Word 教程系列第 2 篇】Word 中如何设置每页的表格都有表头

Chapter V virtual memory exercise

One card can sell tens of millions, and the business expansion is faster than that of players: you don't understand the Jianghu of star cards
随机推荐
Counting sorting and stability of sorting
Use conditional breakpoints in vscode (based on GDB)
第四章 存储器管理练习
Three communication skills in software testing
[API packet capturing in selenium automation] installation and configuration of browsermobproxy
VSCode里使用条件断点(基于GDB)
C语言-单词分析解析
计数排序和排序的稳定性
Add the premise of ganggan
Prometeus 2.36.0 新特性
论文解读(DCN)《Towards K-means-friendly Spaces: Simultaneous Deep Learning and Clustering》
Didn't find an internship. He summed it up
2022年PMP项目管理考试敏捷知识点(4)
Would like to ask, how to open a stock account? Is it safe to open an account online?
入行数字IC验证后会做些什么?
Oil monkey script learning
【状态机设计】Moore、Mealy状态机、三段式、二段式、一段式状态机书写规范
Matlab learning notes (6) upsample function and downsample function of MATLAB
frameworks/base/core/res/res/values/symbols. Xml:3915: error: no definition for declared symbol solution
LINQ linked table query