Thursday, 7 December 2023

Apply average blur to an image in OpenCV

 

Average blurring

It is also known as mean blurring used to reduce the noise and smooth the image.

 

How Average blurring works?

Step 1: First you need to define a smaller square or rectangle kernel matrix. In general, kernels are of size 3x3, 5x5, or 7x7.

 

Step 2: Select the portion that is same as kernel size in the image (start by placing the kernel in the top left corner of the image), at each position of the kernel, the value of the center pixel is replaced with the average of all the pixel values within the kernel.

 

The average or mean is computed by adding the values of all the pixels within the kernel and dividing by the number of pixels.

 

Formula for the new value of the image pixel is given below.

 

Suppose, you have a kernel of size 3x3, then the output value is calculated using below formula.e

 

output(x, y) = (input(x-1, y-1) + input(x, y-1) + input(x+1, y-1) +

               input(x-1, y) + input(x, y) + input(x+1, y) +

               input(x-1, y+1) + input(x, y+1) + input(x+1, y+1)) / 9

 

How edge rows, columns are handled here?

There are multiple ways to address corner rows and columns.

 

a.   Do not process corner rows and columns: Apply the average blurring only to interior pixels

a.   Zero padding: Pixels outside the image boundary are considered to have a value of zero.

 

To make the things simple, I am going by not processing the corners.


As you see the image, first I placed the kernel of size 3x3 on top left corner (0, 0) of the array. Pixel at index [1][1] is the center pixel of the array, let’s find the average of the elements and replace it array [1][1] with average value.

 

Average = (1+10+10+2+10+20+3+10+20)/9

             = 86/9

             = 9.5

              = 9 (rounded to 9)

 

Now the diagram is changed like below.

 


Move the kernel to 1pixel right and calculate the average like above

 


After applying the procedure for all the elements array results are like below.

 


 

Let’s keep the edge row, column values as it is.

 

 


Following python application do the same (update without edge rows and columns).

 

average_blur_on_arrays.py

import numpy as np

# Define a sample 2D array (image) with pixel values
image = np.array([[1, 10, 10, 4, 5, 6],
                  [2, 10, 20, 20, 4, 70],
                  [3, 10, 20, 30, 4, 80],
                  [5, 10, 20, 30, 5, 90],
                  [5, 5, 90, 150, 0, 100],
                  [6, 70, 80, 90, 100, 5]])

# Define a 3x3 average blur kernel
kernel = np.array([[1, 1, 1],
                   [1, 1, 1],
                   [1, 1, 1]], dtype=float) / 9

# Create an empty result array of the same size as the image
result = np.zeros_like(image, dtype="uint8")

# Iterate through interior pixels (ignoring the corner rows and columns)
for i in range(1, image.shape[0] - 1):
    for j in range(1, image.shape[1] - 1):
        neighborhood = image[i-1:i+2, j-1:j+2]  # Extract the 3x3 neighborhood
        result[i, j] = np.sum(neighborhood * kernel)  # Apply the kernel

# Convert the result to integer values
result = np.round(result).astype(np.uint8)

# Print the original and blurred images
print("Original Image:")
print(image)
print("\nBlurred Image (Ignoring Corners):")
print(result)

Output

[[ 0  0  0  0  0  0]
 [ 0  9 14 12 24  0]
 [ 0 11 18 17 37  0]
 [ 0 18 40 38 54  0]
 [ 0 32 60 62 63  0]
 [ 0  0  0  0  0  0]]

How to blur image using OpenCV?

Using cv2.blur method, we can apply average blur affect on the image.

 

Signature

dst = cv2.blur(src, ksize[, anchor[, borderType]])

 

Following table summarizes the parameters of blur method.

 

Parameter

Description

src

Source image where you want to apply the blur affect

ksize

It is a tuple, specifies kernel size.

anchor

It is optional, the default value is (-1, -1), indicating that the anchor is at the center of the kernel.

borderType

It is optional parameter, specifies how to handle borders of the image. Following constants are supported.

a.   cv2.BORDER_CONSTANT,

b.   cv2.BORDER_REPLICATE,

c.    cv2.BORDER_REFLECT,

d.   cv2.BORDER_WRAP

 

 

Example

blurred_image = cv.blur(image, (3, 3))

 

Find the below working application.

 

average_blur.py

import cv2 as cv

image = cv.imread('gateway_of_india.png')
cv.imshow('Original image', image)

blurred_image = cv.blur(image, (3, 3))
cv.imshow('Blurred image 3*3 kernel size', blurred_image)

blurred_image = cv.blur(image, (5, 5))
cv.imshow('Blurred image 5*5 kernel size', blurred_image)

blurred_image = cv.blur(image, (7, 7))
cv.imshow('Blurred image 7*7 kernel size', blurred_image)

cv.waitKey(0)

# Close the OpenCV windows
cv.destroyAllWindows()

Output

Original image




Blur with 3*3 kernel size




Blur with 5*5 kernel size

 


 

Blur with 7*7 kernel size

 


 

Note

Higher the kernel size, we get more blur

 

References

https://www.youtube.com/watch?v=ZoaEDbivmOE

 



Previous                                                    Next                                                    Home

No comments:

Post a Comment