Rescale pixel intensities of an image in Python

In this tutorial, we will see how to rescale the pixel intensities of image.

Colour images are arrays of pixel values of RED, GREEN, and BLUE. These RGB values range from 0 – 255.

Every pixel will have an RGB value depending on the intensities of these colours. Now to process these images with RGB pixel values is a huge task, especially in the field of machine learning where huge chunks of data are processed. So it is very important to rescale simpler pixel values for the ease of computation.

How to rescale pixel intensities of an image in Python?

Firstly let’s import necessary modules

import matplotlib.pyplot as plt
from numpy import asarray
from PIL import Image

Now we will get the image. Note that the image is in still in the form of pixels we need to convert it into arrays.

image = Image.open('image path')
print(image.mode)
plt.imshow(image)
image_pixels=asarray(image)

Here we have used pillow module to open the image and numpy function asarray to convert into arrays.

The output looks like this

RGB

Rescale pixel intensities of an image in Python

credits: wallpaperplay.com

Now we will see what are the maximum and minimum and the mean pixel densities we have got.

std=image_pixels.std()
print(std,”std”)
mean=image_pixels.mean()

print(image_pixels.max(),”max”)
print(image_pixels.min(),”min”)
print(mean,”mean”)

OUTPUT

91.78171626356098 std
255 max
0 min
109.53139837139598 mean

Since we have got the mean values we will subtract the mean value from all the pixel values.

And then divide them by the standard deviation of the pixel values.

 

mean_pixels=image_pixels-mean
mean_std_pixels=mean_pixels/std

Now we have got the rescaled pixel values.

Leave a Reply