Image processing in Python

In computer science, Image processing is a process of enhancing the image or extracting some information from the image.

In Python, there are two main libraries that we can benefit from for Image processing tasks.

1 - Pillow which is a fork from PIL (Python Imaging Library)
2- OpenCV (Open Source Computer Vision)

I found out for basic image processing tasks working with Pillow is easier.

An image is a matrix of pixels. In grayscale images, each pixel can be presented with one value. The value shows the intensity of the pixel. In another word, it shows how dark or bright the pixel is. Depends on the library you are using the value can be a decimal number between 0 and 1 or a number between 0 and 255.



In the coloured images, the pixel value is a three column array. PIL uses RGB order and Open CV uses BGR order. Each column represents the value between 0 and 255.




Below, is the method you can use to show the image histogram of PIL images. 
It checks if the image is coloured or grayscale then shows the values of pixels accordingly.

def showimagehist(image,title=""):
 
    imagearray=array(image)
    fig=figure(figsize=(15, 5))
    fig.suptitle(title, fontsize=16)
    columns = 2
    rows = 1
    fig.add_subplot(rows, columns, 1)
    if (len(imagearray.shape)==3): 
        hist(imagearray[:,:,0].flatten(),color='red')
        hist(imagearray[:,:,1].flatten(),color='green')
        hist(imagearray[:,:,2].flatten(),color='blue')
    else:
        hist(imagearray.flatten(),color='black')
    fig.add_subplot(rows, columns, 2) 
    hist(imagearray.flatten(),color='navy')

You can compare the histogram of coloured and grayscale of my dog's photo.

With ImageOps module, you can easily equalize or normalize your image.

Equalizing an image is a process of applying a non-linear mapping to the input image, in order to create a uniform distribution of grayscale values in the output image



Normalizing an image is a process of removing a percentage of the lightest and darkest pixels from the histogram.



Both image normalization and equalization play a key factor in machine learning. You can start exploring image processing by using this self-explanatory jupyter  notebook
https://github.com/Azadehkhojandi/imageprocessingbasics/blob/master/imageprocessing.ipynb

Comments