How To Divide An Image Into Blocks and Extract Features with OpenCV?

Divide An Image Into 5x5 Blocks In Python And Compute Histogram For Each Block (1)

In today’s world where we have face recognition security systems and driverless cars, we need to know how images and image processing work. Some numerous tools and tricks make image processing easier. Using models such as convolutional neural networks and libraries such as OpenCV in Python, we can easily process images and get important data from it. Images are unstructured datasets that contain valuable information for data analysis, hence data scientists and analysts must convert them into comprehendible graphs and charts.

Dividing images into smaller blocks and patches can help obtain relevant statistics or features independently. The size of these blocks can be considered depending on specific requirements. One common size for these patches is 5×5 and information can be obtained from these blocks by computing their histogram.

In this article, we will first understand the process of diving images into smaller blocks, and then step-by-step we will implement it in Python. Let’s get started.

How Image Block Division Works

There are three main steps involved in breaking down an image into 5×5 blocks and computing their histogram. They are:

  • Image Division: The image is divided into smaller patches or blocks according to the size defined by the user. The blocks or patches usually overlap with one another to ensure that the entire image is covered and no part of it is left out.
  • Histogram Computation: For each of these blocks, a histogram is computed to visualize the distribution of the pixels of the image in that block. It represents the image content in that block.
  • Feature Extraction: These histograms can be further used for analyzing the image data and classification tasks.

In the next section, we will implement the above steps using some Python libraries such as CV2, matplotlib and numpy.

Suggested: Matplotlib Histogram from Basic to Advanced.

Python Code to Divide Image into Blocks

Step 1: The very first step is to import the required modules.

In this program, we will import three modules that we will need. They are: CV2 module which stands for Computer Vision 2, used for image processing programs, Numpy or the numerical python which is used for computation purposes and matplotlib for plotting our histograms.

import cv2
import numpy as np
from matplotlib import pyplot as plt

Step 2: Now we will load our image in the program using cv2. I will be using the picture given below, you can use any image you want.

image = cv2.imread('path_of_your_image.jpg', cv2.IMREAD_GRAYSCALE)
Our Image
Our Image

Step 3: Now we will divide the image into blocks of size 5×5 and compute the histograms for each block.

block_size = 5

# Initializing list to store histograms for each block
block_histograms = []

# Iterating over blocks
for i in range(0, image.shape[0], block_size):
    for j in range(0, image.shape[1], block_size):
        # Extract block
        block = image[i:i+block_size, j:j+block_size]
        
        # Computing histogram for block
        histogram, _ = np.histogram(block.flatten(), bins=256, range=[0,256])
        
        # Appending histogram to list
        block_histograms.append(histogram)

Step 4: The final step in the implementation of this method is visualizing the Histograms.

# Plotting histograms for each block
for i, histogram in enumerate(block_histograms):
  try:
    plt.subplot(5, 5, i+1)
    plt.plot(histogram)
    plt.title(f'Block {i+1}')
    plt.axis('off')
  except ValueError:
    break

plt.tight_layout()
plt.show()

The output will be:

The Imgae Is Divided Into 5x5 Blocks And Each Block Is Represented As A Histogram
The Image Is Divided Into 5×5 Blocks And Each Block Is Represented As A Histogram.

Recommended: Visualizing Colors In Images Using Histograms – Python OpenCV.

The entire program code is given below:

#importing the three required modules
import cv2
import numpy as np
from matplotlib import pyplot as plt

#loading the image and defining the block size
image = cv2.imread('/content/example_image.jpg', cv2.IMREAD_GRAYSCALE)
block_size = 5

# Initializing list to store histograms for each block
block_histograms = []

# Iterating over blocks
for i in range(0, image.shape[0], block_size):
    for j in range(0, image.shape[1], block_size):
        # Extract block
        block = image[i:i+block_size, j:j+block_size]
        
        # Computing histogram for block
        histogram, _ = np.histogram(block.flatten(), bins=256, range=[0,256])
        
        # Appending histogram to list
        block_histograms.append(histogram)
  
# Plotting histograms for each block
for i, histogram in enumerate(block_histograms):
  try:
    plt.subplot(5, 5, i+1)
    plt.plot(histogram)
    plt.title(f'Block {i+1}')
    plt.axis('off')
  except ValueError:
    break

plt.tight_layout()
plt.show()

Summary

Dividing images into blocks is a handy technique for localized image analysis. With just a few lines of Python code leveraging OpenCV and NumPy, you can break an image down into patches and extract features like histograms from each block. What other ways could you use this method for your image processing work?