Gaussian blur/smoothing is the most commonly used smoothing technique to eliminate noises in images and videos. In this technique, an image should be convolved with a Gaussian kernel to produce the smoothed image.
You may define the size of the kernel according to your requirement. But the standard deviation of the Gaussian distribution in X and Y direction should be chosen carefully considering the size of the kernel such that the edges of the kernel is close to zero. Here I have shown the 3 x 3 and 5 x 5 Gaussian kernels.
Gaussian Blur on Images with OpenCV
OpenCV has an in-built function to perform Gaussian blur/smoothing on images easily. All you have to specify is the size of the Gaussian kernel with which your image should be convolved.Here is a simple program demonstrating how to smooth an image with a Gaussian kernel with OpenCV.
Copy and paste the above code snippet into your IDE and run it. Please note that you have to replace "D:/My OpenCV Website/Lotus.jpeg" in the code with a valid location to an image in your computer. Then you should see set of images like the below.
Explanation
Let"s go through the above OpenCV example program line by line. // Read the image file
Mat image = imread("D:/My OpenCV Website/Lotus.jpeg");
// Check for failure
if (image.empty())
{
cout << "Could not open or find the image" << endl;
cin.get(); //wait for any key press
return -1;
}
This code segment loads an image from the file "D:/My OpenCV Website/Lotus.jpeg" and returns it as a Mat object.
If the returned Mat object is empty, exit the program by returning from the main function. This is an important validation because calling imshow() on empty Mat object might crash your program.
//Blur the image with 3x3 Gaussian kernel Mat image_blurred_with_3x3_kernel; GaussianBlur(image, image_blurred_with_3x3_kernel, Size(3, 3), 0); The above function performs the Gaussian blur/smoothing operation with a 3 x 3 Gaussian filter on the original image and stores the smoothed image in the image_blurred_with_3x3_kernel Mat object. Each channel in the original image is processed independently. The width and height of the kernel should be odd. The standard deviation in the X direction and the Y direction of the Gaussian distribution will be calculated based on the size of the kernel.
//Blur the image with 5x5 Gaussian kernel Mat image_blurred_with_5x5_kernel; GaussianBlur(image, image_blurred_with_5x5_kernel, Size(5, 5), 0); The above function performs the Gaussian blur/smoothing operation with a 5 x 5 Gaussian filter on the original image and stores the smoothed image in the image_blurred_with_5x5_kernel Mat object. Each channel in the original image is processed independently. The width and height of the kernel should be odd. The standard deviation in the X direction and the Y direction of the Gaussian distribution will be calculated based on the size of the kernel.
//Define names of the windows String window_name = "Lotus"; String window_name_blurred_with_3x3_kernel = "Lotus Blurred with 3 x 3 Gaussian Kernel"; String window_name_blurred_with_5x5_kernel = "Lotus Blurred with 5 x 5 Gaussian Kernel"; // Create windows with above names namedWindow(window_name); namedWindow(window_name_blurred_with_3x3_kernel); namedWindow(window_name_blurred_with_5x5_kernel); // Show our images inside the created windows. imshow(window_name, image); imshow(window_name_blurred_with_3x3_kernel, image_blurred_with_3x3_kernel); imshow(window_name_blurred_with_5x5_kernel, image_blurred_with_5x5_kernel); The above code segment creates windows and shows images in them.
WaitKey(0); // Wait for any keystroke in the window destroyAllWindows(); //destroy all opened windows The program waits for any keystroke. After any key is pressed, all opened windows will be destroyed.
Summary
In the above section, you have learned,- How to load an image from a file
- How to perform the Gaussian smoothing/blur operation on images with a Gaussian filter.
- How to create windows and display images
- How to wait without exiting the program until the user presses a key
- How to destroy created windows
Gaussian Blur on Videos with OpenCV
Now I am going to show you how to perform Gaussian blur/smoothing on a video using an OpenCV C++ example. This is pretty much similar to the previous example.It is recommended to go through the first in order to understand the following example better.
//Uncomment the following line if you are compiling this code in Visual Studio
//#include "stdafx.h"
#include
Эти семь эффектов уже были ранее доступны для Motion 5, а теперь появилась версия работающая в Final Cut X.
Gradient Blur
Этот эффект создаёт градиентное размытие между двумя точками.
Circle Blur
Этот эффект создаёт размытие в круге. Используйте элементы управления на экране, чтобы контролировать настройку фильтра.
Soft Focus
Этот эффект создаёт ощущение размытой линзы.
Compound Blur
Этот фильтр подволяет размывать изображение на основе другого изображения. По принципу adjustment layers. Как пример, посмотрите на этот кадр используемый в качестве маски:
А вот результат размытия, в данном случае размыты те места, где яркость слоя-маски больше.
Следующие параметры показывают настройки фильтра при параметрах, когда размытие применяется в местах прозрачности кадра-маски.
Unsharp Mask
Этот фильтр имеет более тонкие настройки, чем стандартный фильтр Файнал ката.
Создаёт картинку более приближенную к реальному расфокусу камеры.
Для сравнения вот вам стандартный эффект gaussian blur
Вот крупный план этого эффекта на другом кадре
Gaussian Blur версия
Модель размытия создаётся на основе диафрагмы объектива, которая имеет идеально круглую форму. Большинство реальных диафрагм в линзах имеют в своей основе форму многоугольника, где число сторон больше 7. Чтобы изменить количество сторон этого многоугольника есть соответствующая настройка:
и как результат:
Channel Blur
Размывает определённые каналы:
Он включает в себя скрипт для программы Motion template tool . Если у вас она не установлена, скачайте её и установите. Это бесплатная программа для установки самодельных темплейтов в Motion. MTT корректно установит все плагины в папки Final cut X. Если же вы не хотите её устанавливать, то можете сделать всё вручную. Закиньте эффекты в папку Home / Movies / Motion Templates / Effects / Blur:
Usually, image processing software will provide blur filter to make images blur.
There are many algorithms to implement blur, one of them is called Gaussian Blur algorithm. It utilizes Gaussian distribution to process images.
This article is to introduce Gaussian Blur algorithm, you will find this a simple algorithm. In fact, it is a kind of data smoothing which can be used in many situations.
1. Gaussian Blur theory
The so called blur can be understood as taking a pixel as the average value of its surrounding pixels.
On the above graph, 2 is the center point, the surrounding points are 1.
The center point will take the average value of its surrounding points, it will be 1. From value perspective, it"s a smoothing. On graphic, it"s a blur effect. The center point will lose its detail.
Obviously if the value range is very large, the blur effect is very strong.
The above are graphs of original, 3 pixels blur radius and 10 pixels blur radius. The bigger the blur radius, the more blur the picture is.
The question now is if every point will get the average value of surrounding points, then how should we allocate weight?
If we just use simple average, it"s unreasonable, because images are continuous, the closer the points in distance, the closer the relationship between points. Hence the weighted average is more reasonable than simple average, the close the points in distance, the larger the weight.
2. Weight of normal distribution
Normal distribution is an acceptable weight distribution model.
On graphic, normal distribution is a Bell-shaped curve, the closer to the center, the bigger the value.
3. Gaussian function
The normal distribution above is one dimensional, the graph is two dimensional. We need two dimensional normal distribution.
The density function of normal distribution is called Gaussian function. The one dimension format is:
Here μ is the average of x, Because center point is the origin point when calculating average value, so μ equals to 0.
Based on the one dimension function , we can derive the two dimensional Gaussian function.
With this function, we can calculate the weight of each point.
4. Weight matrix
Assume the coordinate of the center point is (0,0), then the coordinates of 8 points which are nearest to it are:
To calculate the weight matrix, we need to set the value of σ, σ=1.5, then the weight matrix of blur radius 1 is
The sum of the weights of these 9 points is 0.4787147. If only calculate the Weighted average of these 9 points, then the sum should be 1, hence the above 9 values should divide 0.4787147.
5. Calculate Gaussian Blur
With weight matrix, we can calculate the value of Gaussian Blur.
Assume we have 0 pixels now, the gray value(0-255):
Each point multiplies its weight value:
Add these 9 values up, we will get the Gaussian Blur value of the center point.
Repeat this process for all other points, then we will get graph after Gaussian blur.
6. The process for the points at borders
If a point is at the border, there are not enough points, what should we do?
One solution is to copy all the existing points to respective places to form a new matrix.