The Wayback Machine - https://web.archive.org/web/20241124122615/https://www.geeksforgeeks.org/box-blur-algorithm-with-python-implementation/
Open In App

Box Blur Algorithm – With Python implementation

Last Updated : 30 Dec, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
The pixels in an image are represented as integers. After blurring each pixel ‘x’ of the resulting image has a value equal to the average of the pixels surrounding ‘x’ including ‘x’. For example, consider a 3 * 3 image as   image = \begin{bmatrix} 1 & 1  & 1\\  1 & 7 & 1\\  1 & 1 & 1 \end{bmatrix}  Then, the resulting image after blur is blurred_image =  \begin{bmatrix} 1 \end{bmatrix} So, the pixel of blurred image is calculated as (1 + 1 + 1 + 1 + 7 + 1 + 1 + 1 + 1) / 9 = 1.66666 = 1

Box Blur Algorithm –

Box blur is also known as box linear filter. Box blurs are frequently used to approximate Gaussian blur. A box blur is generally implemented as an image effect that affects the whole screen. The blurred colour of the current pixel is the average of the current pixel’s colour and its 8 neighbouring pixels.
Note: For each 3 * 3 pixel matrix there is one blurred pixel calculated as above.
FOr Example, Consider the below image.   image = \begin{bmatrix} 7 & 4 & 0 & 1\\  5 & 6 & 2 & 2\\  6 & 10 & 7 & 8\\  1 & 4 & 2 & 0 \end{bmatrix} It’s blurred image is given below:   blurred\_image = \begin{bmatrix} 5 & 4\\  4 & 4 \end{bmatrix} Explanation: There are four 3 * 3 matrix possible in the above image. So there are 4 blurred pixel in the resulting image. The four matrices are:
  \begin{bmatrix} 7 & 4 & 0\\  5 & 6 & 2\\  6 & 10 & 7 \end{bmatrix},

  \begin{bmatrix} 4 & 0 & 1\\  6 & 2 & 2\\  10 & 7 & 8 \end{bmatrix},

 \begin{bmatrix} 5 & 6 & 2\\  6 & 10 & 7\\  1 & 4 & 2 \end{bmatrix},
and
 \begin{bmatrix} 6 & 2 & 2\\  10 & 7 & 8\\  4 & 2 & 0 \end{bmatrix} 
  Implementation in Python:
def square_matrix(square):
    """ This function will calculate the value x 
       (i.e. blurred pixel value) for each 3 * 3 blur image.
    """
    tot_sum = 0
      
    # Calculate sum of all the pixels in 3 * 3 matrix
    for i in range(3):
        for j in range(3):
            tot_sum += square[i][j]
              
    return tot_sum // 9     # return the average of the sum of pixels
  
def boxBlur(image):
    """
    This function will calculate the blurred 
    image for given n * n image. 
    """
    square = []     # This will store the 3 * 3 matrix 
                 # which will be used to find its blurred pixel
                   
    square_row = [] # This will store one row of a 3 * 3 matrix and 
                    # will be appended in square
                      
    blur_row = []   # Here we will store the resulting blurred
                    # pixels possible in one row 
                    # and will append this in the blur_img
      
    blur_img = [] # This is the resulting blurred image
      
    # number of rows in the given image
    n_rows = len(image) 
      
    # number of columns in the given image
    n_col = len(image[0]) 
      
    # rp is row pointer and cp is column pointer
    rp, cp = 0, 0 
      
    # This while loop will be used to 
    # calculate all the blurred pixel in the first row 
    while rp <= n_rows - 3: 
        while cp <= n_col-3:
              
            for i in range(rp, rp + 3):
                  
                for j in range(cp, cp + 3):
                      
                    # append all the pixels in a row of 3 * 3 matrix
                    square_row.append(image[i][j])
                      
                # append the row in the square i.e. 3 * 3 matrix 
                square.append(square_row)
                square_row = []
              
            # calculate the blurred pixel for given 3 * 3 matrix 
            # i.e. square and append it in blur_row
            blur_row.append(square_matrix(square))
            square = []
              
            # increase the column pointer
            cp = cp + 1
          
        # append the blur_row in blur_image
        blur_img.append(blur_row)
        blur_row = []
        rp = rp + 1 # increase row pointer
        cp = 0 # start column pointer from 0 again
      
    # Return the resulting pixel matrix
    return blur_img
  
# Driver code
image = [[7, 4, 0, 1], 
        [5, 6, 2, 2], 
        [6, 10, 7, 8], 
        [1, 4, 2, 0]]
          
print(boxBlur(image))

                    
Output:
[[5, 4], 
[4, 4]]
Test case 2:
image = [[36, 0, 18, 9], 
         [27, 54, 9, 0], 
         [81, 63, 72, 45]]
  
print(boxBlur(image))

                    
Output:
[[40, 30]]
  Further Read: Box Blur using PIL library | Python

Previous Article
Next Article

Similar Reads

Python OpenCV | cv2.blur() method
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.blur() method is used to blur an image using the normalized box filter. The function smooths an image using the kernel which is represented as: Syntax: cv2.blur(src, ksize[, dst[, anchor[, borderType]]]) Parameters: src: It is the image whose is to be blur
2 min read
Python - Adaptive Blur in Wand
Adaptive Blur is a kind of blur. The only difference is that blur intensity around the detectable edges in image is less while, it is greater on areas without edges. Adaptive Blur can be done using adaptive_blur function. Syntax : C/C++ Code wand.image.adaptive_blur(radius="radius_value", sigma="sigma_value", channel = "opt
1 min read
Wand - blur() function in Python
Blurring Image means making an image fuzzy or hazy. A blur image is indefinite and it is unable to see an image clearly. Blur is of many types, like - Adaptive blur, Gaussian blur, Selective Blur etc. In order to blur an image we use blur() function. blur() function takes three arguments. Example : Syntax : wand.image.blur(radius="radius_value
2 min read
Wand blur() function - Python
The blur() function is an inbuilt function in the Python Wand ImageMagick library which is used to blur the image. Syntax: blur(radius, sigma, channel) Parameters: This function accepts three parameters as mentioned above and defined below: radius: This parameter is used to specify the value of radius which is the size of the gaussian aperture.sigm
2 min read
Pgmagick blur() method - Python
The blur() function is an inbuilt function in the Pgmagick library which is used to to add blur filter to the image. The function returns the true value on success. Syntax: blur( radius, sigma ) Parameters: This function accept two parameters as mentioned above and described below: radius:This parameter stores the value of the blur radius. sigma: I
2 min read
OpenCV Python Program to blur an image
Note: This post contains codes that cannot be run using an online compiler. Please make sure that you have Python 2.7 and cv2 module installed before trying to run the program on your system. Hi everyone! I read a brilliant work by Aditya Prakash – OpenCV C++ Program to blur an image, so I decided to come up with something similar but this time in
2 min read
OpenCV C++ Program to blur an image
The following is the explanation to the C++ code to blur an Image in C++ using the tool OpenCV. Things to know: (1) The code will only compile in Linux environment. (2) Compile command: g++ -w article.cpp -o article `pkg-config --libs opencv` (3) Run command: ./article (4) The image bat.jpg has to be in the same directory as the code. Before you ru
5 min read
Node Jimp | Blur
The blur() function is an inbuilt function in Nodejs | Jimp which uses a blur algorithm that produces a similar effect to a Gaussian blur. Syntax: blur(r, cb()) Parameter: r: This parameter stores the radius of the blur.cb: This is an optional parameter that is invoked when compilation is complete. Input Images: Setup Environment: npm init -y Insta
1 min read
Node.js GM blur() Function
The blur() function is an inbuilt function in the GraphicsMagick library which is used to add a blur filter to the image. The function returns the true value of success. Syntax: blur( radius, sigma ) Parameters: This function accepts two parameters as mentioned above and described below: radius: This parameter stores the value of the blur radius.si
1 min read
ML | Reinforcement Learning Algorithm : Python Implementation using Q-learning
Prerequisites: Q-Learning technique. Reinforcement Learning is a type of Machine Learning paradigms in which a learning algorithm is trained not on preset data but rather based on a feedback system. These algorithms are touted as the future of Machine Learning as these eliminate the cost of collecting and cleaning the data. In this article, we are
6 min read
Genetic Algorithm for Reinforcement Learning : Python implementation
Most beginners in Machine Learning start with learning Supervised Learning techniques such as classification and regression. However, one of the most important paradigms in Machine Learning is Reinforcement Learning (RL) which is able to tackle many challenging tasks. It is an aspect of Machine learning where an agent learns to behave in an environ
5 min read
Implementation of Perceptron Algorithm for NOT Logic Gate
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
2 min read
Implementation of Perceptron Algorithm for AND Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
2 min read
Implementation of Perceptron Algorithm for OR Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
2 min read
Implementation of Perceptron Algorithm for NOR Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
3 min read
Implementation of Perceptron Algorithm for NAND Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
3 min read
Implementation of Perceptron Algorithm for XOR Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
3 min read
Implementation of Perceptron Algorithm for XNOR Logic Gate with 2-bit Binary Input
In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: [Tex]\[ \begin{array}{c} \hat{y}=\Theta\left(w_{1} x_{1}+w_{2} x_{2}+\ldots+w_{n} x_{n}+b\right) \\ =\Theta(\mathbf{w} \cdot \mathbf{x}+b) \\ \text { where } \Theta(v)=\left\{\begin{arra
3 min read
Implementation of Whale Optimization Algorithm
Previous article Whale optimization algorithm (WOA) talked about the inspiration of whale optimization, its mathematical modeling and algorithm. In this article we will implement a whale optimization algorithm (WOA) for two fitness functions 1) Rastrigin function    2) Sphere function  The algorithm will run for a predefined number of maximum itera
6 min read
Implementation of Grey Wolf Optimization (GWO) Algorithm
Previous article Grey wolf optimization- Introduction talked about inspiration of grey wolf optimization, and its mathematical modelling and algorithm. In this article we will implement grey wolf optimization (GWO) for two fitness functions - Rastrigin function and Sphere function. The aim of Grey wolf optimization algorithm is to find minimize of
7 min read
Python | Box-Cox Transformation
Imagine you are watching a horse race and like any other race, there are fast runners and slow runners. So, logically speaking, the horse which came first and the fast horses along with it will have the smaller difference of completion time whereas the slowest ones will have a larger difference in their completion time. We can relate this to a very
5 min read
Calculate Percentage of Bounding Box Overlap, for Image Detector Evaluation using Python
There occurs various instances when you need to calculate by how much percentage two boxes in an image overlap. Did a similar situation has occurred to you? Read the article below to know how you can deal with that problem. What we exactly do is obtain the dimensions of two boxes from the user. Then, calculate the intersection of two boxes and the
3 min read
Implementation of Ridge Regression from Scratch using Python
Prerequisites: Linear Regression Gradient Descent Introduction: Ridge Regression ( or L2 Regularization ) is a variation of Linear Regression. In Linear Regression, it minimizes the Residual Sum of Squares ( or RSS or cost function ) to fit the training examples perfectly as possible. The cost function is also represented by J. Cost Function for Li
4 min read
Implementation of K-Nearest Neighbors from Scratch using Python
Instance-Based LearningK Nearest Neighbors Classification is one of the classification techniques based on instance-based learning. Models based on instance-based learning to generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a rel
8 min read
Linear Regression Implementation From Scratch using Python
Linear Regression is a supervised learning algorithm which is both a statistical and a machine learning algorithm. It is used to predict the real-valued output y based on the given input value x. It depicts the relationship between the dependent variable y and the independent variables xi ( or features ). The hypothetical function used for predicti
4 min read
Implementation of Page Rank using Random Walk method in Python
Prerequisite: Page Rank Algorithm and Implementation, Random Walk In Social Networks page rank is a very important topic. Basically page rank is nothing but how webpages are ranked according to its importance and relevance of search. All search engines use page ranking. Google is the best example that uses page rank using the web graph. Random Walk
3 min read
Implementation of Logistic Regression from Scratch using Python
Introduction:Logistic Regression is a supervised learning algorithm that is used when the target variable is categorical. Hypothetical function h(x) of linear regression predicts unbounded values. But in the case of Logistic Regression, where the target variable is categorical we have to strict the range of predicted values. Consider a classificati
5 min read
Implementation of XOR Linked List in Python
Prerequisite: XOR Linked List An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory-efficient version of Doubly Linked List can be created using only one space for the address field with every node. This memory efficient Doubly Linked List is called XOR Linked List or Memory
6 min read
Sklearn | Multi-dimensional Scaling (MDS) Python Implementation from Scratch
Scikit-learn (sklearn) is a Python machine-learning package that is open-source and free to use. It is Python's most popular machine-learning library, and it is extensively used in business and academics. Scikit-learn includes a wide range of machine learning methods, including supervised learning (classification, regression), unsupervised learning
10 min read
Implementation of Radius Neighbors from Scratch in Python
Radius Neighbors is also one of the techniques based on instance-based learning. Models based on instance-based learning generalize beyond the training examples. To do so, they store the training examples first. When it encounters a new instance (or test example), then they instantly build a relationship between stored training examples and this ne
8 min read
three90RightbarBannerImg