Семь бесплатных блюров для Final Cut X. Сглаживание путем усреднения

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.

Эти семь эффектов уже были ранее доступны для 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:


Иногда ошибки gaussian_blur.aex и другие системные ошибки AEX могут быть связаны с проблемами в реестре Windows. Несколько программ может использовать файл gaussian_blur.aex, но когда эти программы удалены или изменены, иногда остаются "осиротевшие" (ошибочные) записи реестра AEX.

В принципе, это означает, что в то время как фактическая путь к файлу мог быть изменен, его неправильное бывшее расположение до сих пор записано в реестре Windows. Когда Windows пытается найти файл по этой некорректной ссылке (на расположение файлов на вашем компьютере), может возникнуть ошибка gaussian_blur.aex. Кроме того, заражение вредоносным ПО могло повредить записи реестра, связанные с Adobe After Effects. Таким образом, эти поврежденные записи реестра AEX необходимо исправить, чтобы устранить проблему в корне.

Редактирование реестра Windows вручную с целью удаления содержащих ошибки ключей gaussian_blur.aex не рекомендуется, если вы не являетесь специалистом по обслуживанию ПК. Ошибки, допущенные при редактировании реестра, могут привести к неработоспособности вашего ПК и нанести непоправимый ущерб вашей операционной системе. На самом деле, даже одна запятая, поставленная не в том месте, может воспрепятствовать загрузке компьютера!

В связи с подобным риском мы настоятельно рекомендуем использовать надежные инструменты очистки реестра, такие как WinThruster (разработанный Microsoft Gold Certified Partner), чтобы просканировать и исправить любые проблемы, связанные с gaussian_blur.aex. Используя очистку реестра , вы сможете автоматизировать процесс поиска поврежденных записей реестра, ссылок на отсутствующие файлы (например, вызывающих ошибку gaussian_blur.aex) и нерабочих ссылок внутри реестра. Перед каждым сканированием автоматически создается резервная копия, позволяющая отменить любые изменения одним кликом и защищающая вас от возможного повреждения компьютера. Самое приятное, что устранение ошибок реестра может резко повысить скорость и производительность системы.


Предупреждение: Если вы не являетесь опытным пользователем ПК, мы НЕ рекомендуем редактирование реестра Windows вручную. Некорректное использование Редактора реестра может привести к серьезным проблемам и потребовать переустановки Windows. Мы не гарантируем, что неполадки, являющиеся результатом неправильного использования Редактора реестра, могут быть устранены. Вы пользуетесь Редактором реестра на свой страх и риск.

Перед тем, как вручную восстанавливать реестр Windows, необходимо создать резервную копию, экспортировав часть реестра, связанную с gaussian_blur.aex (например, Adobe After Effects):

  1. Нажмите на кнопку Начать .
  2. Введите "command " в строке поиска... ПОКА НЕ НАЖИМАЙТЕ ENTER !
  3. Удерживая клавиши CTRL-Shift на клавиатуре, нажмите ENTER .
  4. Будет выведено диалоговое окно для доступа.
  5. Нажмите Да .
  6. Черный ящик открывается мигающим курсором.
  7. Введите "regedit " и нажмите ENTER .
  8. В Редакторе реестра выберите ключ, связанный с gaussian_blur.aex (например, Adobe After Effects), для которого требуется создать резервную копию.
  9. В меню Файл выберите Экспорт .
  10. В списке Сохранить в выберите папку, в которую вы хотите сохранить резервную копию ключа Adobe After Effects.
  11. В поле Имя файла введите название файла резервной копии, например "Adobe After Effects резервная копия".
  12. Убедитесь, что в поле Диапазон экспорта выбрано значение Выбранная ветвь .
  13. Нажмите Сохранить .
  14. Файл будет сохранен с расширением.reg .
  15. Теперь у вас есть резервная копия записи реестра, связанной с gaussian_blur.aex.

Следующие шаги при ручном редактировании реестра не будут описаны в данной статье, так как с большой вероятностью могут привести к повреждению вашей системы. Если вы хотите получить больше информации о редактировании реестра вручную, пожалуйста, ознакомьтесь со ссылками ниже.

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.

You have to choose a right size of the kernel to define the neighborhood of each pixel. If it is too large, small features of the image may be disappeared and the image will look blurred. If it is too small, you cannot eliminate noises in the image.

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.

#include using namespace cv; using namespace std; int main(int argc, char** argv) { // 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; } //Blur the image with 3x3 Gaussian kernel Mat image_blurred_with_3x3_kernel; GaussianBlur(image, image_blurred_with_3x3_kernel, Size(3, 3), 0); //Blur the image with 5x5 Gaussian kernel Mat image_blurred_with_5x5_kernel; GaussianBlur(image, image_blurred_with_5x5_kernel, Size(5, 5), 0); //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); waitKey(0); // Wait for any keystroke in the window destroyAllWindows(); //destroy all opened windows return 0; }
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 #include using namespace cv; using namespace std; int main(int argc, char* argv) { //open the video file for reading VideoCapture cap("D:/My OpenCV Website/A Herd of Deer Running.mp4"); // if not success, exit program if (cap.isOpened() == false) { cout << "Cannot open the video file" << endl; cin.get(); //wait for any key press return -1; } //Define names of the window String window_name_of_original_video = "Original Video"; String window_name_of_video_blurred_with_5x5_kernel = "Video Blurred with 5 x 5 Gaussian Kernel"; // Create a window with above names namedWindow(window_name_of_original_video, WINDOW_NORMAL); namedWindow(window_name_of_video_blurred_with_5x5_kernel, WINDOW_NORMAL); while (true) { Mat frame; bool bSuccess = cap.read(frame); // read a new frame from video if (bSuccess == false) { cout << "Found the end of the video" << endl; break; } //Blur the frame with 5x5 Gaussian kernel Mat frame_blurred_with_5x5_kernel; GaussianBlur(frame, frame_blurred_with_5x5_kernel, Size(5, 5), 0); //show the frames in the created windows imshow(window_name_of_original_video, frame); imshow(window_name_of_video_blurred_with_5x5_kernel, frame_blurred_with_5x5_kernel); //wait for for 10 ms until any key is pressed. //If the "Esc" key is pressed, break the while loop. //If the any other key is pressed, continue the loop //If any key is not pressed withing 10 ms, continue the loop if (waitKey(10) == 27) { cout << "Esc key is pressed by user. Stoppig the video" << endl; break; } } return 0; } Copy and paste the above code snippet into your IDE and run it. Please note that you have to replace "D:/My OpenCV Website/A Herd of Deer Running.mp4" in the code with a valid location to a video in your computer. Then you should see a smoothed/blurred video along with the original video.