[go: up one dir, main page]

0% found this document useful (0 votes)
14 views11 pages

ICT-4202, DIP Lab Manual - 3

This document provides an introduction to image processing using the Pillow library in Python. It discusses opening, displaying, rotating, resizing and saving images. Key methods covered include open(), show(), rotate(), resize() and save(). It also discusses obtaining image properties, flipping images vertically and horizontally, cropping images and reading multiple images from a folder. The goal is to introduce students to the Pillow library and performing basic image operations.

Uploaded by

dontdisturb058
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views11 pages

ICT-4202, DIP Lab Manual - 3

This document provides an introduction to image processing using the Pillow library in Python. It discusses opening, displaying, rotating, resizing and saving images. Key methods covered include open(), show(), rotate(), resize() and save(). It also discusses obtaining image properties, flipping images vertically and horizontally, cropping images and reading multiple images from a folder. The goal is to introduce students to the Pillow library and performing basic image operations.

Uploaded by

dontdisturb058
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Institute of Information Technology

Jahangirnagar University
Savar, Dhaka-1342

Lab Manual

Course Code: ICT-4202

Course Title: Digital Image Processing Lab

Lab No.: 3
Lab Title: IMAGE PROCESSING USING PILLOW LIBRARY OF
PYTHON

Prepared by

Mehrin Anannya
Assistant Professor
Institute of Information Technology

INTRODUCTION TO IMAGE PROCESSING USING


1
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Jahangirnagar University

Lab Title: IMAGE PROCESSING USING PILLOW LIBRARY OF


PYTHON OBJECTIVE: To introduce students with Image processing library named
pillow and some works on color models.

Lab Contents:
● Introduction to PILLOW library
● Image Works using Pillow library
● Reading multiple images using pillow library
● Convert OpenCV image to PIL image in Python
● Additive and subtractive color
● Color spaces in RGB

Theory: with Hands on Practice:


Introduction to PILLOW:
Python Imaging Library (expansion of PIL) is the de facto image processing package for Python
language. It incorporates lightweight image processing tools that aid in editing, creating and
saving images. Support for Python Imaging Library got discontinued in 2011, but a project
named pillow forked the original PIL project and added Python3.x support to it. Pillow was
announced as a replacement for PIL for future usage. Pillow supports numerous image file
formats including BMP, PNG, JPEG, and TIFF. The library encourages adding support for newer
formats in the library by creating new file decoders.

INTRODUCTION TO IMAGE PROCESSING USING


2
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
The basic difference between OpenCV image and PIL image is OpenCV follows BGR color
convention and PIL follows RGB color convention and the method of converting will be based
on this difference.
PIL install in anaconda:
In Anaconda prompt, write – pip install pillow

Image Works using Pillow library


Open Image using open():
The PIL.Image.Image class represents the image object. This class provides the open() method
that is used to open the image.
from PIL import Image
img = Image.open("Flower.jpeg")

#Note: Location of image should be relative only if the image is in the same directory as the
Python program, otherwise absolute (full) path of the image should be provided.
Displaying the image using show():
This method is used to display the image. For displaying the image Pillow first converts the
image to a .png format (on Windows OS) and stores it in a temporary buffer and then displays it.
Therefore, due to the conversion of the image format to .png some properties of the original
image file format might be lost (like animation). Therefore, it is advised to use this method only
for test purposes.
img.show();

INTRODUCTION TO IMAGE PROCESSING USING


3
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Obtaining information about the opened image:
A) Getting the mode (color mode) of the image: The mode attribute of the image tells the type
and depth of the pixel in the image. A 1-bit pixel has a range of 0-1, and an 8-bit pixel has a
range of 0-255. There are different modes provided by this module. Few of them are:

Mode Description
1 1-bit pixels, black and white
L 8-bit pixels, Greyscale
P 8-bit pixels, mapped to any other mode using a color palette
RGB 3×8-bit pixels, true color
RGBA 4×8-bit pixels, true color with transparency mask

print(img.mode)
B) Getting the size of the image: This attribute provides the size of the image. It returns a tuple
that contains width and height.
print(img.size)
C) Getting the format of the image: This method returns the format of the image file.
print(img.format)
Rotating an image using rotate(): After rotating the image, the sections of the image having no
pixel values are filled with black (for non-alpha images) and with completely transparent pixels
(for images supporting transparency)
r_img = img.rotate(40)
r_img.show()

Flipping the Image


Image.transpose() is used to transpose the image (flip or rotate in 90 degree steps).

INTRODUCTION TO IMAGE PROCESSING USING


4
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Keywords FLIP_TOP_BOTTOM and FLIP_LEFT_RIGHT will be passed to transpose method
to flip it.

FLIP_TOP_BOTTOM – returns an original image flipped Vertically


FLIP_LEFT_RIGHT – returns an original image flipped Horizontally

# importing PIL Module


from PIL import Image

# open the original image


original_img = Image.open("geek.jpg")

# Flip the original image vertically


vertical_img = original_img.transpose(method=Image.FLIP_TOP_BOTTOM)
vertical_img.save("vertical.png")

vertical_img.show()

# close all our files object


original_img.close()
vertical_img.close()

Resizing an image using resize(): Interpolation happens during the resize process, due to which
the quality of image changes whether it is being upscaled (resized to a higher dimension than

INTRODUCTION TO IMAGE PROCESSING USING


5
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
original) or downscaled (resized to a lower Image then original). Therefore resize() should be
used cautiously and while providing suitable value for resampling argument.
size = (100, 300)
r_img = img.resize(size)
r_img.show()
Saving an image using save(): While using the save() method Destination_path must have the
image filename and extension as well. The extension could be omitted in Destination_path if the
extension is specified in the format argument.
from PIL import Image

size = (40, 40)


img = Image.open(r"geek.jpg")

print("Original size of the image")


print(img.size)

# resizing the image


r_img = img.resize(size, resample = Image.BILINEAR)

# resized_test.png => Destination_path


r_img.save("resized_test.jpg")

# Opening the new image


img = Image.open(r"resized_test.jpg")

print("\nNew size of the image")


print(img.size)

INTRODUCTION TO IMAGE PROCESSING USING


6
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Cropping the Image
Cropping is the process of selecting only a part of the image. The crop() method is used to crop a
rectangular portion of any image.

Syntax:
PIL.Image.crop(box = None)
Parameters:
box: a 4-tuple defining the left, upper, right, and lower pixel coordinate.

# Importing Image class from PIL module


from PIL import Image

# Opens a image in RGB mode


im = Image.open(r"geek.jpg")

# Size of the image in pixels


# (size of original image)
# (This is not mandatory)
width, height = im.size

# Setting the points for cropped image


left = 5
top = height / 4
right = 164
bottom = 3 * height / 4

INTRODUCTION TO IMAGE PROCESSING USING


7
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
# Cropped image of above dimension # (It will not change original image)
im1 = im.crop((left, top, right, bottom))

# Shows the image in image viewer


im1.show()

Reading multiple images using pillow library


#Read all images from the folder
import os
from PIL import Image
from matplotlib import pyplot as plt
root = "Images"
fnames = os.listdir(root)
len(fnames)
fig, axs=plt.subplots(nrows=1, ncols=6,figsize=(20,20))
axs=axs.flatten()
for i in range(6):
filepath=os.path.join(root, fnames[i])
img=Image.open(filepath)
axs[i].imshow(img)
axs[i].axis('off')
axs[i].set_title(fnames[i])
plt.show()

INTRODUCTION TO IMAGE PROCESSING USING


8
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Convert OpenCV image to PIL image in Python

import cv2
from PIL import Image

# Open image using openCV2


opencv_image = cv2.imread("logo.png")
# Notice the COLOR_BGR2RGB which means that the color is
# converted from BGR to RGB
color_coverted = cv2.cvtColor(opencv_image, cv2.COLOR_BGR2RGB)

# Displaying the Scanned Image by using cv2.imshow() method


cv2.imshow("OpenCV Image", opencv_image)

# Displaying the converted image


pil_image = Image.fromarray(color_coverted)
pil_image.show()

# waits for user to press any key


# (this is necessary to avoid Python kernel form crashing)
cv2.waitKey(0)

# closing all open windows


cv2.destroyAllWindows()

Additive and subtractive color:

INTRODUCTION TO IMAGE PROCESSING USING


9
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
https://pavilion.dinfos.edu/Article/Article/2355687/additive-subtractive-color-models/#:~:text=In
%20the%20subtractive%20color%20model,black%2C%20also%20known%20as%20CMYK.

Color Spaces in RGB:


Please follow the given link:
https://www.geeksforgeeks.org/color-spaces-in-opencv-python/?ref=lbp
import cv2

image = cv2.imread('Images\Flower.jpeg')
B, G, R = cv2.split(image)
# Corresponding channels are separated

cv2.imshow("original", image)
cv2.waitKey(0)

cv2.imshow("blue", B)
cv2.waitKey(0)

cv2.imshow("Green", G)
cv2.waitKey(0)

cv2.imshow("red", R)
cv2.waitKey(0)
cv2.destroyAllWindows()

INTRODUCTION TO IMAGE PROCESSING USING


10
PYTHON
Prepared using materials from the internet, especially GeekforGeeks
Tasks:

INTRODUCTION TO IMAGE PROCESSING USING


11
PYTHON
Prepared using materials from the internet, especially GeekforGeeks

You might also like