Image Processing in Python
Introduction
Python is very popular language for data manipulation as it is very easy to understand and easy to implement. Python has a unique milestones on the way of data science in today’s world. Python is the first choice of data scientists. before going to our topic, at first we have to know about Image processing. So what is Image processing in python and why it is used … So basically image processing is manipulation and analysis of images using set of algorithms. Images are significant tool in data science. In python image is treated as array(vectors) . There are many libraries in python for image processing. we can perform various tasks like displaying images, basic manipulations like cropping, flipping, rotating ,Image Segmentation, Classification and feature extractions, Image restoration and Image recognition using python. For image processing we have many options in python like SciPy, numPy, scikit image, openCV, simpleCV, PIL etc..
Summarize Details about image
from PIL import Image# Open the image form working directoryimage = Image.open('/content/371afa7e0bb2981e1ce3fa750859780d.jpg')# summarize some details about the image
print(image.format) #format of image
print(image.size) #size of image
print(image.mode) #mode of image#output
#JPEG
#(736, 552)
#RGB
Here we are going to use PIL for import the image and get some details about the imported image.
Display Image
we have already imported the image using PIL, now we are going to display image using matplotlib. Matplotlib is plotting library in python. which is used to plot graph of numerical expressions and charts.
from matplotlib import image
from matplotlib import pyplot# load image as pixel array image=image.imread('/content/371afa7e0bb2981e1ce3fa750859780d.jpg')# summarize shape of the pixel array
print(image.dtype) #datatype of this image pixel array
print(image.shape) #shap of image# display the array of pixels as an image
pyplot.imshow(image)
pyplot.show()
here we have imported pyplot from matplotlib. Pyplot provides the state-machine interface to the underlying plotting library in matplotlib. and methods like show() and imshow () is useful to display an image.
Convert Image to numPY Array
here we are going to convert an image to numPY array. numPY supports large, multi-dimensional arrays and matrices.
from PIL import Image
from numpy import asarray# load the image
image = Image.open('/content/371afa7e0bb2981e1ce3fa750859780d.jpg')# convert image to numpy array
data = asarray(image)
print(type(data))
# summarize shape
print(data.shape)# create Pillow image
image2 = Image.fromarray(data)
print(type(image2))
# summarize image details
print(image2.mode)
print(image2.size)
print(data)
we have imported the image before. so now convert it to numpy array using asarray() method. If we want to convert it back to image we can use Image.fromarray(array) method.
Crop some portion of image
we can crop perticular dimension of image using crop() method
from PIL import Image
from matplotlib import pyplot# Opens a image in RGB mode
im = Image.open(r"/content/371afa7e0bb2981e1ce3fa750859780d.jpg")# Size of the image in pixels (size of orginal image)
# (This is not mandatory)
width, height = im.size# Setting the points for cropped image
left = 100
top = height / 4
right = 300
bottom = 3 * height / 4# Cropped image of above dimension
# (It will not change orginal image)
im1 = im.crop((left, top, right, bottom))# Shows the image in image viewer
pyplot.imshow(im1)
pyplot.show()
Here we give dimensions as argument of crop() functions. so image is cropped as given dimensions.
Horizontal collage of images
here we have made image array and add an image one by one in it using for loop. after that we have saved result image in a variable and plot the image using matplotlib.
import sys
from PIL import Image
from matplotlib import pyplotimages = [Image.open(x) for x in ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']]
#store image array in a variablewidths, heights = zip(*(i.size for i in images))
#total width of all the images
total_width = sum(widths)#here height is taken as height of image which has maximum height from array
max_height = max(heights)new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save('test.jpg')
pyplot.imshow(new_im)
pyplot.show()
Vertical collage of image
Here for making vertical collage of image we are going to use numpy. we are going to convert image array to numpy array and will process over it.
vstack() method of numpy is used to make sequence of input arrays vertically to make a single array.
so here we will use this technique to make vertical collage
import numpy as np
import PIL
from PIL import Image
from matplotlib import pyplot
list_im = ['Test1.jpg', 'Test2.jpg', 'Test3.jpg']
imgs = [ PIL.Image.open(i) for i in list_im ]# pick the image which is the smallest, and resize the others to match it (can be arbitrary image shape here)min_shape = sorted( [(np.sum(i.size), i.size ) for i in imgs])[0][1]imgs_comb = np.hstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )# save that beautiful picture
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta.jpg' )# for a vertical stacking it is simple: use vstackimgs_comb = np.vstack( (np.asarray( i.resize(min_shape) ) for i in imgs ) )
imgs_comb = PIL.Image.fromarray( imgs_comb)
imgs_comb.save( 'Trifecta_vertical.jpg' )
pyplot.imshow(imgs_comb)
pyplot.show()
final result image is stored in another array. and now convert it to image using fromarray() method and plot image using matplotlib.
Create image from numpy array
Here we create a numpy array using zeros() method. as argument we have passed dimensions like width, height and datatype.
import matplotlib.pyplot as plt
import numpy as npw,h=512,512 # Declared the Width and Height of an Image
t=(h,w,3) # To store pixels# Creation of Array
A=np.zeros(t,dtype=np.uint8)
for i in range(h):
for j in range(w):
A[i,j]=[i%256,j%256,(i+j)%256] # Assigning Colors to Each pixeli=Image.fromarray(A,"RGB")
i.show()
pyplot.imshow(i)
pyplot.show()
we have assigned colors to each and every pixels in array and after that converting array to image and plot it using matplotlib
Generate Image with random data
Here we have are going to use random() method of numpy. After creating an array we will convert it into image and plot the image using pylab.
from pylab import imshow, show, get_cmap
from numpy import random
Z = random.random((50,50)) # Test data
imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()
Generate Gray scale image
we can give gray effect to image which we have generate randomly using numpy and pylab.
import pylab as plt
import numpy as np
Z = np.random.random((500,500)) # Test dataplt.imshow(Z, cmap='gray', interpolation='nearest')
plt.show()
here interpolation stands for arrangement of pixels . interpolation =’nearest’ means arrangement of pixels is done nearby each other.
Image with cv2
OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.imwrite()
method is used to save an image to any storage device.
import matplotlib.pyplot as plt
import numpy as np
import cv2img = cv2.imread('Test1.jpg')
plt.imshow(img)
here we have used opencv . Openncv is very userful vision library . By default color format of this Library is defer from normal libraries. Normally we use RGB format ,but it uses BGR format so that color is changed in output.
Add noise to image
we are going to add noise to above image.
first we will generate noise randomly in numpy array and add the noise to image.
first import the image and assign to a variable. and do following steps.
this is output image after giving noise effect to image. here strength is high so that noise is also high.
Conclusion
It is very interesting to work with images in python. Python is ocean. there are many libraries in python for image processing. check all to get know about them.