Box filter opencv python

OpenCV — Box Filter

The Box Filter operation is similar to the averaging blur operation; it applies a bilateral image to a filter. Here, you can choose whether the box should be normalized or not.

You can perform this operation on an image using the boxFilter() method of the imgproc class. Following is the syntax of this method −

boxFilter(src, dst, ddepth, ksize, anchor, normalize, borderType)

This method accepts the following parameters −

  • src − A Mat object representing the source (input image) for this operation.
  • dst − A Mat object representing the destination (output image) for this operation.
  • ddepth − A variable of the type integer representing the depth of the output image.
  • ksize − A Size object representing the size of the blurring kernel.
  • anchor − A variable of the type integer representing the anchor point.
  • Normalize − A variable of the type boolean specifying weather the kernel should be normalized.
  • borderType − An integer object representing the type of the border used.

Example

The following program demonstrates how to perform the Box Filter operation on an image.

import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.Point; import org.opencv.core.Size; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.imgproc.Imgproc; public class BoxFilterTest < public static void main( String[] args ) < // Loading the OpenCV core library System.loadLibrary( Core.NATIVE_LIBRARY_NAME ); // Reading the Image from the file and storing it in to a Matrix object String file = "E:/OpenCV/chap11/filter_input.jpg"; Mat src = Imgcodecs.imread(file); // Creating an empty matrix to store the result Mat dst = new Mat(); // Creating the objects for Size and Point Size size = new Size(45, 45); Point point = Point(-1, -1); // Applying Box Filter effect on the Image Imgproc.boxFilter(src, dst, 50, size, point, true, Core.BORDER_DEFAULT); // Writing the image Imgcodecs.imwrite("E:/OpenCV/chap11/boxfilterjpg", dst); System.out.println("Image Processed"); >>

Assume that following is the input image filter_input.jpg specified in the above program.

Читайте также:  Блок оценки в html

Filter Input

Output

On executing the program, you will get the following output −

If you open the specified path, you can observe the output image as follows −

Источник

3 фильтра изображений в OpenCV – двусторонний, Box и 2d

Фильтрация изображений — это процесс изменения изображения путем изменения его оттенков или цвета пикселя. Он также используется для увеличения яркости и контрастности. В этом уроке мы узнаем о нескольких типах фильтров изображений OpenCV.

Двусторонний фильтр

OpenCV предоставляет функцию bilateralFilter() для применения двустороннего фильтра к изображению. Двусторонний фильтр может очень хорошо уменьшить нежелательный шум, сохраняя при этом четкие края. Синтаксис функции приведен ниже:

cv2.bilateralFilter(src, dst, d, sigmaSpace, borderType)

Параметры

  • src — обозначает источник изображения. Это может быть 8-битное или одноканальное изображение с плавающей запятой.
  • dst — обозначает целевое изображение того же размера. Его тип будет таким же, как у образа src.
  • d — обозначает диаметр окрестности пикселя (целочисленный тип), который используется при фильтрации. Если его значение отрицательное, то оно вычисляется из sigmaSpace.
  • sigmaColor — обозначает сигму фильтра в цветовом пространстве.
  • sigmaSpace – обозначает сигму фильтра в координатном пространстве.

Рассмотрим следующий пример:

import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread(r'C:\Users\DEVANSH SHARMA\baloon.jpg',1) kernel = np.ones((5,5),np.float32)/25 blur = cv2.bilateralFilter(img,9,75,75) plt.subplot(121),plt.imshow(img),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(blur),plt.title('Bilateral Filter') plt.xticks([]), plt.yticks([]) cv2.imshow("Image",blur)

Двусторонний фильтр

Box-фильтр

Мы можем выполнить этот фильтр, используя функцию boxfilter(). Это похоже на операцию усреднения размытия. Синтаксис функции приведен ниже:

cv2. boxfilter(src, dst, ddepth, ksize, anchor, normalize, bordertype)

Параметры

  • src — обозначает источник изображения. Это может быть 8-битное или одноканальное изображение с плавающей запятой.
  • dst — обозначает целевое изображение того же размера. Его тип будет таким же, как у образа src.
  • ddepth — обозначает глубину выходного изображения.
  • ksize — размывает размер ядра.
  • anchor — обозначает точки привязки. По умолчанию его значение указывает на координаты(-1,1), что означает, что якорь находится в центре ядра.
  • normalize — это флаг, указывающий, должно ли ядро быть нормализовано или нет.
  • borderType — целочисленный объект, представляющий тип используемой границы.

Рассмотрим следующий пример:

import cv2 import numpy as np # using imread('path') and 0 denotes read as grayscale image img = cv2.imread(r'C:\Users\DEVANSH SHARMA\baloon.jpg',1) img_1 = cv2.boxFilter(img, 0,(7,7), img,(-1,-1), False, cv2.BORDER_DEFAULT) #This is using for display the image cv2.imshow('Image',img_1) cv2.waitKey(3) # This is necessary to be required so that the image doesn't close immediately. #It will run continuously until the key press. cv2.destroyAllWindows()

Box-фильтр

Фильтр 2D

Он объединяет образ с ядром. Мы можем выполнить эту операцию с изображением, используя метод Filter2D(). Синтаксис функции приведен ниже:

cv2.Filter2D(src, dst, kernel, anchor =(-1,-1))

Параметры

  • src — представляет входное изображение.
  • dst — обозначает целевое изображение того же размера. Его тип будет таким же, как у образа src.
  • kernel — это ядро свертки, одноканальная матрица с плавающей запятой. Если вы хотите применить разные ядра к разным каналам, разбейте изображение на отдельную цветовую плоскость с помощью команды split(), обрабатывая их по отдельности.
  • anchor — обозначает точки привязки, по умолчанию его значение Point (-1,1), что означает, что он находится в центре ядра.
  • borderType — целочисленный объект, представляющий тип используемой границы.

Рассмотрим следующий пример:

import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread(r'C:\Users\DEVANSH SHARMA\baloon.jpg',1) kernel = np.ones((5,5),np.float32)/25 dst = cv2.filter2D(img,-1,kernel) plt.subplot(121),plt.imshow(img),plt.title('Original') plt.xticks([]), plt.yticks([]) plt.subplot(122),plt.imshow(dst),plt.title('Filter2D') plt.xticks([]), plt.yticks([]) plt.show()

Источник

Box filter opencv python

As in one-dimensional signals, images also can be filtered with various low-pass filters (LPF), high-pass filters (HPF), etc. LPF helps in removing noise, blurring images, etc. HPF filters help in finding edges in images.

OpenCV provides a function cv.filter2D() to convolve a kernel with an image. As an example, we will try an averaging filter on an image. A 5×5 averaging filter kernel will look like the below:

\[K = \frac \begin 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \\ 1 & 1 & 1 & 1 & 1 \end\]

The operation works like this: keep this kernel above a pixel, add all the 25 pixels below this kernel, take the average, and replace the central pixel with the new average value. This operation is continued for all the pixels in the image. Try this code and check the result:

filter.jpg

Image Blurring (Image Smoothing)

Image blurring is achieved by convolving the image with a low-pass filter kernel. It is useful for removing noise. It actually removes high frequency content (eg: noise, edges) from the image. So edges are blurred a little bit in this operation (there are also blurring techniques which don’t blur the edges). OpenCV provides four main types of blurring techniques.

1. Averaging

This is done by convolving an image with a normalized box filter. It simply takes the average of all the pixels under the kernel area and replaces the central element. This is done by the function cv.blur() or cv.boxFilter(). Check the docs for more details about the kernel. We should specify the width and height of the kernel. A 3×3 normalized box filter would look like the below:

\[K = \frac \begin 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 1 \end\]

Note If you don’t want to use a normalized box filter, use cv.boxFilter(). Pass an argument normalize=False to the function.

Check a sample demo below with a kernel of 5×5 size:

blur.jpg

2. Gaussian Blurring

In this method, instead of a box filter, a Gaussian kernel is used. It is done with the function, cv.GaussianBlur(). We should specify the width and height of the kernel which should be positive and odd. We also should specify the standard deviation in the X and Y directions, sigmaX and sigmaY respectively. If only sigmaX is specified, sigmaY is taken as the same as sigmaX. If both are given as zeros, they are calculated from the kernel size. Gaussian blurring is highly effective in removing Gaussian noise from an image.

If you want, you can create a Gaussian kernel with the function, cv.getGaussianKernel().

The above code can be modified for Gaussian blurring:

gaussian.jpg

3. Median Blurring

Here, the function cv.medianBlur() takes the median of all the pixels under the kernel area and the central element is replaced with this median value. This is highly effective against salt-and-pepper noise in an image. Interestingly, in the above filters, the central element is a newly calculated value which may be a pixel value in the image or a new value. But in median blurring, the central element is always replaced by some pixel value in the image. It reduces the noise effectively. Its kernel size should be a positive odd integer.

In this demo, I added a 50% noise to our original image and applied median blurring. Check the result:

median.jpg

4. Bilateral Filtering

cv.bilateralFilter() is highly effective in noise removal while keeping edges sharp. But the operation is slower compared to other filters. We already saw that a Gaussian filter takes the neighbourhood around the pixel and finds its Gaussian weighted average. This Gaussian filter is a function of space alone, that is, nearby pixels are considered while filtering. It doesn’t consider whether pixels have almost the same intensity. It doesn’t consider whether a pixel is an edge pixel or not. So it blurs the edges also, which we don’t want to do.

Bilateral filtering also takes a Gaussian filter in space, but one more Gaussian filter which is a function of pixel difference. The Gaussian function of space makes sure that only nearby pixels are considered for blurring, while the Gaussian function of intensity difference makes sure that only those pixels with similar intensities to the central pixel are considered for blurring. So it preserves the edges since pixels at edges will have large intensity variation.

The below sample shows use of a bilateral filter (For details on arguments, visit docs).

bilateral.jpg

See, the texture on the surface is gone, but the edges are still preserved.

Additional Resources

Exercises

doxygen

Generated on Wed Jul 19 2023 23:42:43 for OpenCV by 1.8.13

Источник

How to use OpenCV — Box Filter

This tutorial shows you how to use OpenCV — Box Filter.

Answer

To use OpenCV’s box filter, you can follow these steps:

  1. Install OpenCV: If you haven’t already installed OpenCV, you can do so by following the instructions provided on the OpenCV website (https://opencv.org/).
  2. Import OpenCV: In your Python script, import the OpenCV library using the following line of code:
image = cv2.imread('path/to/your/image.jpg')
  • src : The input image.
  • ddepth : The desired depth of the output image (use -1 to keep the same depth as the input).
  • ksize : The size of the kernel (box) to be used for filtering.
  • dst : The output image (optional).

Here's an example that applies a box filter with a kernel size of 5x5:

box_filtered_image = cv2.boxFilter(image, -1, (5, 5))

You can experiment with different kernel sizes to achieve the desired effect.

cv2.imshow('Original Image', image) cv2.imshow('Box Filtered Image', box_filtered_image) cv2.waitKey(0) cv2.destroyAllWindows()

Note

You've successfully applied the box filter to an image using OpenCV.

  1. How to use OpenCV - Adaptive Threshold
  2. How to use OpenCV - Adding Borders
  3. How to use OpenCV - Adding Text
  4. How to use OpenCV - Affine Translation
  5. How to use OpenCV - Bilateral Filter
  6. How to use OpenCV - Blur Averaging
  7. How to use OpenCV - Box Filter
  8. How to use OpenCV - Canny Edge Detection
  9. How to use OpenCV - Color Maps
  10. How to use OpenCV - Colored Image to Binary
  11. How to use OpenCV - Colored Images to GrayScale
  12. How to use OpenCV - Dilation
  13. How to use OpenCV - Distance Transformation
  14. How to use OpenCV - Drawing a Circle
  15. How to use OpenCV - Drawing a Line
  16. How to use OpenCV - Drawing a Rectangle

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Оцените статью