Normalize an Image in OpenCV Python (original) (raw)

Last Updated : 07 May, 2024

Normalization involves adjusting the range of pixel intensity values in an image. Normalization can be beneficial for various purposes, such as improving the contrast or making the image more suitable for processing by other algorithms. In this article, we will explore how to normalize images using OpenCV in Python.

What is Image Normalization?

Image normalization is the process of adjusting the pixel intensity values of an image to a predefined range. This range is typically between 0 and 255 for images with 8-bit depth, where 0 represents black and 255 represents white. Normalization can be performed to improve the contrast of an image or to standardize the pixel values for further processing.

In OpenCV Python, the normalize() function from the cv2 module is used to normalize images. This function allows us to specify the desired range for the pixel intensity values.

Normalize an Image in OpenCV Python

Below are some of the examples by which we can understand about normalizing images in OpenCV Python:

Example 1: Normalizing Grayscale Image

In this example, a grayscale image is read and normalized to enhance contrast using the NORM_MINMAX normalization method. Both the original and normalized images are displayed using OpenCV imshow() function.

Python `

import cv2

Read grayscale image

image = cv2.imread('kl.png', cv2.IMREAD_GRAYSCALE)

Normalize image

normalized_image = cv2.normalize( image, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)

Display original and normalized images

cv2.imshow('Original Image', image) cv2.imshow('Normalized Image', normalized_image) cv2.waitKey(0) cv2.destroyAllWindows()

`

**Output:

j

Example 2: Normalizing Color Image

In this example, a color image is converted to grayscale, then normalized to enhance contrast. The normalized grayscale image is converted back to color and displayed alongside the original image using OpenCV.

Python `

import cv2

Read color image

image = cv2.imread('kl.png')

Convert image to grayscale

gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

Normalize grayscale image

normalized_gray_image = cv2.normalize( gray_image, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)

Convert normalized grayscale image back to color

normalized_color_image = cv2.cvtColor( normalized_gray_image, cv2.COLOR_GRAY2BGR)

Display original and normalized images

cv2.imshow('Original Image', image) cv2.imshow('Normalized Image', normalized_color_image) cv2.waitKey(0) cv2.destroyAllWindows()

`

**Output:

kl