[go: up one dir, main page]

0% found this document useful (0 votes)
51 views8 pages

Digital Image Processing: 1 Objectives

This document provides instructions for installing libraries and performing basic operations on digital images in Python. It discusses using OpenCV, Scipy, Matplotlib, Pillow and NumPy to: 1. Read, display and save images 2. Calculate image histograms 3. Draw shapes and text on images 4. Crop and paste one image onto another The document includes code examples for loading an image, displaying histograms of color channels, drawing on images, and pasting one image onto another. It provides notes on functions for reading, displaying, saving and converting between image formats in each library. Exercises are provided to split an image into RGB channels and perform other basic operations.

Uploaded by

Lê Thanh Tùng
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)
51 views8 pages

Digital Image Processing: 1 Objectives

This document provides instructions for installing libraries and performing basic operations on digital images in Python. It discusses using OpenCV, Scipy, Matplotlib, Pillow and NumPy to: 1. Read, display and save images 2. Calculate image histograms 3. Draw shapes and text on images 4. Crop and paste one image onto another The document includes code examples for loading an image, displaying histograms of color channels, drawing on images, and pasting one image onto another. It provides notes on functions for reading, displaying, saving and converting between image formats in each library. Exercises are provided to split an image into RGB channels and perform other basic operations.

Uploaded by

Lê Thanh Tùng
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/ 8

Ton Duc Thang University

Faculty of Information Technology

505060 - Digital Image Processing


Anh H. Vo
vohoanganh@tdtu.edu.vn
September 26, 2021

1 Objectives
The first laboratory will introduce some conventional libraries in digital image processing and student will
learn to perform several basic operations on digital image.

2 How to install and set environment variables


• Install python libraries for image processing
sudo apt−g e t i n s t a l l python−p i p
p i p i n s t a l l opencv python −3.0.0 − cp34−none−win amd64 . whl
or
p i p i n s t a l l opencv−python
p i p i n s t a l l python3−numpy python3−s c i p y python3−m a t p l o t l i b
pip i n s t a l l p i l l o w
pip i n s t a l l p y t e s s e r a c t

• Run the commands in Window Power-Shell to install libraries.


1 import cv2 as cv
2 import numpy as np
3 import matplotlib
4 from scipy.misc import imread , imsave
5
6
7 print (cv. version )

• Install OpenCV library for Android Studio: link


• Install OpenCV library for Raspberry Pi 3 B+: link

3 The basic functions for image processing


3.1 The basic operations on digital image
In this section, we will introduce the different libraries to read an image from your drive. There are many
popular libaries for image processing such as opencv, scipy, matplotlib, and pillow.

Anh H. Vo - vohoanganh@tdtu.edu.vn 1
Ton Duc Thang University
Faculty of Information Technology

1 import cv2 as cv
2
3
4 img = cv. imread (’lena.jpg ’)
5 cv2. imshow (’First example ’, img)
6 cv2. waitKey (0)
Listing 1: Example shows how to load an image and show it on screen with OpenCV

Note: OpenCV library:


• To read an image: cv2.imread(’file path’) # return : numpy.ndarray
• To show an image: cv2.imshow(’Information’, image)

• To save an image: cv2.imwrite(’file name’, image)

1 from scipy.misc import imread , imshow


2
3
4 img = imread (’lena.jpg ’)
5 imshow (img)
Listing 2: Example shows how to load an image and show it on screen with Scipy

Note: Scipy library:


• To read an image: scipy.misc.imread(’file path’) # return : numpy.ndarray
• To show an image: scipy.misc.imshow(image)

• To save an image: scipy.misc.imsave(’file name’, image)

1 import matplotlib . pyplot as plt


2 import matplotlib .image as mpimg
3
4 plt. figure ()
5 img = mpimg. imread (’lena.jpg ’)
6 plt. imshow (img)
7 plt. title(’First example ’)
8 plt.show ()
Listing 3: Example shows how to load an image and show it on screen with matplotlib

Note: matplotlib library:


• To read an image: matplotlib.image.imread(’path’) # return: numpy.ndarray
• To show an image: matplotlib.pyplot.imshow(image)
• To save an image: matplotlib.pyplot.savefig(’file name’)

Anh H. Vo - vohoanganh@tdtu.edu.vn 2
Ton Duc Thang University
Faculty of Information Technology

1 from PIL import Image


2
3 # PIL. JpegImagePlugin . JpegImageFile
4 image = Image.open(’lena.jpg ’)
5 image.show ()
Listing 4: Example shows how to load an image and show it on screen with Pillow

Note: Pillow library:


• To read an image: PIL.Image.open(’file path’)
• To show an image: image.show()
• To save an image: image.save(’file name’,’image type’)

• To convert PIL.Image to numpy.ndarray: img = np.asarray(image)


• To convert numpy.ndarray to PIL.Image: Image.fromarray(img)

3.2 How to compute the histogram of an image


We use np.histogram function from numpy library to calculate the histogram of an image based on the
number of bin (e.g [0, 255])
1 import numpy as np
2 import cv2
3 import matplotlib . pyplot as plt
4
5 img = cv2. imread (’lena.jpg ’)
6 ## img.ravel () flattened matrix to 1D vector
7 hist , bin = np. histogram (img.ravel (), 256, [0, 256])
8
9 plt.hist(hist)
10 plt.show ()
Listing 5: Example calculates the histogram of an image with numpy and shows it on screen with matplotlib

Note: np.histogram function:


• 1D vector
• The number of bin
• The range of bin

cv2.calcHist function in Opencv library also can be used to calculate the histogram of an image instead
of np.histogram
1 import numpy as np
2 import cv2
3 from matplotlib import pyplot as plt

Anh H. Vo - vohoanganh@tdtu.edu.vn 3
Ton Duc Thang University
Faculty of Information Technology

4
5 img = cv2. imread (’lena.jpg ’)
6 color = (’b’,’g’,’r’)
7 for i,col in enumerate (color):
8 histr = cv2. calcHist ([ img ],[i],None ,[256] ,[0 ,256])
9 plt.plot(histr ,color = col)
10 plt.xlim ([0 ,256])
11 plt.show ()
Listing 6: Example uses cv2.calcHist function to calculate the histogram of an image

Similarly, Image.histogram function of PIL library could be used to compute the histogram of an
image, and pyplot.bar is used to show the histogram result on the screen.
1 import matplotlib . pyplot as plt
2 from PIL import Image
3
4 def getRed ( redVal ):
5 return ’#%02x%02x%02x’ % (redVal , 0, 0)
6
7 image = Image.open("lena.jpg")
8 histogram = image. histogram ()
9 # Take only the Red counts
10 l1 = histogram [0:256]
11 # Take only the Blue counts
12 l2 = histogram [256:512]
13
14 # Take only the Green counts
15 l3 = histogram [512:768]
16 plt. figure (0)
17 # Red histogram
18 for i in range (0, 256):
19 plt.bar(i, l1[i], color = getRed (i),
20 edgecolor = getRed (i), alpha =0.3)
21
22 plt.show ()
Listing 7: Example uses the histogram function with Pillow library

Question:
1. Write a program to show the histogram of the blue channel.
2. Write a program to show the histogram of the green channel.

3.3 The basic operations on digital image


3.3.1 Drawing on Image

1 from PIL import Image , ImageDraw


2

Anh H. Vo - vohoanganh@tdtu.edu.vn 4
Ton Duc Thang University
Faculty of Information Technology

3 blank image = Image.new(’RGBA ’, (400 , 300) , ’white ’)


4 img draw = ImageDraw .Draw( blank image )
5 img draw . rectangle ((70 , 50, 270, 200) , outline =’red ’,
6 fill=’blue ’)
7 img draw .text ((70 , 250) , ’Hello World ’, fill=’green ’)
8 blank image .save(’ drawn image .jpg ’)
Listing 8: Example draws on image with Pillow library

Note: Pillow library:


• To create an new image: PIL.Image.new(’file name’, (w, h), ’white’)
• To draw an image: PIL.Image.draw(image)

• To draw a rectange on an image: image.rectangle((x,y,w,h), outline=color, fill=color)


• To draw a text on an image: image.text((x,y),’Information’, fill=color)

1 import cv2
2 img = cv2. imread (’ the scream .jpg ’)
3 blank = np. zeros ((200 ,200 ,3) ,np.uint8)
4 cv2. rectangle (blank ,(20 ,20) ,(50 ,50) ,(255 ,0 ,0) ,3)
5 cv2. putText (blank ,’Hello world ’ ,(20 ,30) ,
6 cv2. FONT HERSHEY SIMPLEX ,1 ,(0 ,255 ,0))
7 cv2. imshow (’Hello ’,blank)
8 cv2. waitKey (0)
9 cv2. destroyAllWindows ()
Listing 9: Example draws on image of OpenCV library

Note: OpenCV library:


• To create an new image: np.zeros((height, width, 3), np.uint8)
• To draw a rectange on an image: cv2.rectangle(image, (top, left), (bottom, right), (R, G, B),
3)

• To draw a text on an image: cv2.putText(image, ’Information’, (x, y), font, fontscale, (R, G,
B), thickness, cv2.LINE AA)

3.3.2 How to past an image to another image

1 from PIL import Image


2
3 image = Image.open(’ unsplash 01 .jpg ’)
4 logo = Image.open(’logo.png ’)
5 image copy = image.copy ()
6 position = (( image copy .width − logo.width),
7 ( image copy . height − logo. height ))
8 image copy .paste(logo , position )

Anh H. Vo - vohoanganh@tdtu.edu.vn 5
Ton Duc Thang University
Faculty of Information Technology

9 image copy .save(’ pasted image .jpg ’)


Listing 10: Example shows how to past one image to another image of Pillow library

1 import cv2
2 img = cv2. imread (’ the scream .jpg ’)
3 blank = np. zeros ((200 ,200 ,3) ,np.uint8)
4 wb ,hb , cb = blank.shape
5 w,h,c = img.shape
6 img [10: wb +10 ,10: hb +10 ,:] = blank [: ,: ,:]
7 cv2. imshow (’Hello ’,img)
8 cv2. waitKey (0)
Listing 11: Example shows how to crop a region image with OpenCV library

Anh H. Vo - vohoanganh@tdtu.edu.vn 6
Ton Duc Thang University
Faculty of Information Technology

4 Exercises
Exercise 1: Write a program to split an input image with RGB space into three images which present on
Red, Green, Blue channels and then save on your drive.

Exercise 2: Write a program to show the histogram of images for each channel which is splitted from the
previous exercise.
Exercise 3: Write a program to crop a region of input image and save it:
• PIL library (hint: image.crop((x, y, w, h)) function )
• OpenCV library (hint: image[y : y + h, x : x + h] with x, y are vertical, horizontal value coordinate
plane of image and w, h are the width and height of region)
Exercise 4: Write a program to draw a rectangle, circle, eclipse shape on image and put text Hello world
on an input image by OpenCV library.
• To draw a circle, you need its center coordinates, radius and thickness.
1 cv2. circle (img ,(xc , yc), r, (0 ,0 ,255) , −1)

• To draw a rectangle, you need top-left corner and bottom-right corner of rectangle.
1 cv2. rectangle (img ,(384 ,0) ,(510 ,128) ,(0 ,255 ,0) ,3)

• To draw the ellipse, we need to pass several arguments. One argument is the center location
(x,y). Next argument is axes lengths (major axis length, minor axis length). angle is the angle of
rotation of ellipse in anti-clockwise direction. startAngle and endAngle denotes the starting and
ending of ellipse arc measured in clockwise direction from major axis
1 cv2. ellipse (img ,(256 ,256) ,(100 ,50) ,0,0,180,255, − 1)

• To put text on image:


1 font = cv2. FONT HERSHEY SIMPLEX
2 cv2. putText (img ,’OpenCV ’ ,(10 ,500) , font ,
4 ,(255 ,255 ,255)
3 ,2,cv2. LINE AA )

Exercise 5: Write a program to overlay a smaller image on a larger image using OpenCV library.
Exercise 6: Write a program to try on many different glasses for an input of face image.

Exercise 7: Write a program to add, subtract, multiply two image and then the results are saved with
format jpg, bmp. What do you observe?
Exercise 8: Write functions to add two images f1 (x) and f2 (x) based on the following equations:
• g(x, y) = (1 − a)f1 (x, y) + af2 (x, y), where a from [0, 1] (Image blending)
• g(x, y) = a.f1 (x, y) + b.f2 (x, y) + k, where a, b from [0, 1] and k = 0

Exercise 9: Write a function to compute a mean image from many different images and than it is saved
on your drive.

Anh H. Vo - vohoanganh@tdtu.edu.vn 7
Ton Duc Thang University
Faculty of Information Technology

5 References
1. Reference 1
2. Reference 2

Anh H. Vo - vohoanganh@tdtu.edu.vn 8

You might also like