Python Imaging Library(PIL) is an open source package for image processing that performs read,
write and simple mathematical and logical manipulations on the image. In this
post, let’s demonstrate the uses of PIL library in performing various operations
on images. For plotting the image alone, matplotlib will be used.
Python script:
from PIL import Image,ImageChops
import matplotlib.pyplot as plt
img = Image.open("poppies.jpg");
plt.imshow(img);
plt.show();
#Grayscale Image
Gimg = img.convert('L');
plt.imshow(Gimg,cmap='gray');
plt.show();
#Display Red channel,
Green channel and Blue Channel
r,g,b = img.split()
c1 =
ImageChops.constant(r,0);
Red =
Image.merge("RGB",(r,c1,c1));
plt.imshow(Red);
plt.show();
Green = Image.merge("RGB",(c1,g,c1));
plt.imshow(Green);
plt.show();
Blue =
Image.merge("RGB",(c1,c1,b));
plt.imshow(Blue);
plt.show();
EXPLANATION:
img =
Image.open("poppies.jpg");
The Image module from PIL is used
to read the image ‘poppies.jpg’ into the variable ‘img’ as RGB image.
Gimg =
img.convert('L');
The above syntax converts the RGB
image into grayscale.
plt.imshow(Gimg,cmap='gray');
The command mentioned displays the monochromatic
image with the colormap ‘gray’.
r,g,b = img.split();
This splits the RGB image ‘img’ and
stores the Red component in ‘r’, green component in ‘g’and blue component in
‘b’
Let’s keep the Red channel undisturbed
and replace other channels with zeros.
c1 =
ImageChops.constant(r,0);
Create an image of same size of
‘img’ filled with zeros.
The above syntax will replace all
the values in the image ‘r’ with the constant value ‘0’
Red =
Image.merge("RGB",(r,c1,c1));
plt.imshow(Red);
plt.show();
Merge the three components to
create RGB image. For red component, image ‘r’ is used and for green and blue
component, the zero filled image ‘c1’ is used.
Similarly, the other channels are
displayed as RGB components.
Yellow =
Image.merge("RGB",(r,g,c1));
plt.imshow(Yellow);
plt.show();
Red and Green channels are used
while the blue channel is filled with zeros.
The Variable explorer shows the
list of variables used in the python script. The type of the variable is Image
and it contains 640 rows by 353 columns.
The Mode ‘RGB’ indicates that the
image is color image with Red, Green and Blue components. The Mode ‘L’
indicates that the image is grayscale or monochrome.
Let’s explore the pixel values of
the image ‘img’. In the Variable explorer window, right click on the
corresponding variable and click Edit.
The pixel values with respect to the position will be displayed in a
table format.
NOTE:
Use the help() syntax to learn more about the modules.
EXAMPLE: help(Image)
This displays all the available functions in the module ‘Image’
from the PIL library
0 comments:
Enjoyed Reading? Share Your Views