NumPy also called Numerical Python is an amazing library open-source Python library for data manipulation and scientific computing. It is used in the domain of linear algebra, Fourier transforms, matrices, and the data science field. which is used. NumPy arrays are way faster than Python Lists.You must have known about Image processing Libraries such as OpenCV, Python Image Library(PIL), Scikit-Image, and many more. If you would like to know more about Image Processing Libraries in Python, then must check out this article.🙂
Top Python Libraries For Image Processing In 2021
For more articles related to machine learning and Python 😊😊 , check out this Link
You must be wondering that NumPy is also used for Image Processing. The fundamental idea is that we know images are made up of NumPy ndarrays. So we can manipulate these arrays and play with images. I hope this blog will give you a broad overview of NumPy for Image Processing.😍
This article was published as a part of the Data Science Blogathon.
Type below commands in Anaconds Prompt and all the required will get installed.
# installation of required Libraries
pip install numpy
pip install matplotlib
pip install Pillow
We are using numpy, matplotlib, and Python Imaging Library (PIL) libraries for our further analysis.
# importing all the required libraries
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageOps
To open an image, we are using the open() method from the PIL Image module. Similarly, we can use the matplotlib library to read and show images. It uses an image module for working with images. It offers two useful methods imread() and imshow()
In this analysis, we are using imshow() method to display the image.
Python Code:
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image, ImageOps
img = np.array(Image.open('emma stone.jpg'))
plt.figure(figsize=(8,8))
plt.imshow(img)
plt.show()
In this section, we will see what is the dimension, shape, and data type of an image. To check the size of the image, we are using the Image.size property. Check the below code:
print('# of dims: ',img.ndim) # dimension of an image
print('Img shape: ',img.shape) # shape of an image
print('Dtype: ',img.dtype)
print(img[20, 20]) # pixel value at [R, G, B]
print(img[:, :, 2].min()) # min pixel value at channel B
Output
# of dims : 3 Img shape: (484, 640, 3) Dtype : unit8 [220 216 215 ] 0
Saving ndarray as Image
To save a ndarray as an image, we are using the Imag.save() method.
path = 'emma.jpg'
pil_img = Image.fromarray(img)
pil_img.save(path)Rotating an Image
We are rotating an image from scratch without using the PIL library. If you would like to rotate an image by using the PIL, then use Image.rotate() method.
Algorithm: image(ndarray) -> transpose -> mirror image across y axis (middle column)
Check the below code to rotate an image by 90 degrees in a clockwise direction.
degrees = 90
img = np.array(Image.open('emma_stone.jpg'))
# img = img.sum(2) / (255*3) # converting to grayscale
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(img)
plt.title("original")
img0 = img.copy()
for _ in range(degrees // 90):
img0 = img0.transpose(1, 0, 2)
for j in range(0, img0.shape[1] // 2):
c = img0[:, j, :].copy()
img0[:, j, :] = img0[: , img0.shape[1]-j-1, :]
img0[: , img0.shape[1]-j-1, :] = c
fig.add_subplot(1, 2, 2)
plt.imshow(img0)
plt.title("rotated")
Output
Check the below code to rotate an image by 90 degrees in an anticlockwise direction.
plt.imshow(np.rot90(img))
Output
Converting a color image to a negative image is very simple. You to perform only 3 steps for each pixel of the image
Check the below code to convert an image to a negative image.
fig = plt.figure(figsize=(10, 10))
img_grey = 255*3 - img_grey # 255 * 3 because we added along channel axis previously
fig.add_subplot(1, 2, 1)
plt.imshow(img_grey)
plt.title('Negative of Grey image')
img = 255 - img
fig.add_subplot(1, 2, 2)
plt.imshow(img)
plt.title('Negative of RGB image')
To add black padding around an image, use the below code:
img = np.array(Image.open('emma_stone.jpg'))
img_grey = img.sum(2) / (255*3)
img0 = img_grey.copy()
img0 = np.pad(img0, ((100,100),(100,100)), mode='constant')
plt.imshow(img0)
To split the image into each RGB colors, you can use the below code:
img = np.array(Image.open('emma_stone.jpg'))
img_R, img_G, img_B = img.copy(), img.copy(), img.copy()
img_R[:, :, (1, 2)] = 0
img_G[:, :, (0, 2)] = 0
img_B[:, :, (0, 1)] = 0
img_rgb = np.concatenate((img_R,img_G,img_B), axis=1)
plt.figure(figsize=(15, 15))
plt.imshow(img_rgb)
We can reduce the color intensity depends on our needs. Check the below code for color reduction.
img = np.array(Image.open('emma_stone.jpg'))
# Making Pixel values discrete by first division by // which gives int and then multiply by the same factor
img_0 = (img // 64) * 64
img_1 = (img // 128) * 128
img_all = np.concatenate((img, img_0, img_1), axis=1)
plt.figure(figsize=(15, 15))
plt.imshow(img_all)
We can trim an image in Numpy using Array Slicing. Check the below code for trimming an image using python.
img = np.array(Image.open('emma_stone.jpg'))
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(img)
plt.title('Original')
img0 = img[128:-128, 128:-128, :]
fig.add_subplot(1, 2, 2)
plt.imshow(img0)
plt.title('Trimmed')
We can paste a slice of an image onto another image. Check the below code in Python for pasting a slice of the image.
src = np.array(Image.open('emma_stone.jpg').resize((128, 128)))
dst = np.array(Image.open('emma_stone.jpg').resize((256, 256))) // 4
dst_copy = dst.copy()
dst_copy[64:128, 128:192] = src[32:96, 32:96]
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(src)
plt.title('Original')
fig.add_subplot(1, 2, 2)
plt.imshow(dst_copy)
plt.title('Pasted with slice')
We can also binarize an Image using Numpy. Check the below code to binarize an image.
img = np.array(Image.open('emma_stone.jpg'))
img_64 = (img > 64) * 255
img_128 = (img > 128) * 255
fig = plt.figure(figsize=(15, 15))
img_all = np.concatenate((img, img_64, img_128), axis=1)
plt.imshow(img_all)
Check the below code for flipping an image.
img0 = img.copy()
for i in range(img0.shape[0] // 2):
c = img0[i, :, :].copy()
img0[i, :, :] = img0[img0.shape[0] - i - 1, :, :]
img0[img0.shape[0] - i - 1, :, :] = c
plt.imshow(img0)
Check the below code for Flipping an Image:
img = np.array(Image.open('emma_stone.jpg'))
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(np.flipud(img))
fig.add_subplot(1, 2, 2)
plt.imshow(np.fliplr(img))
If you want to blend two images, then you can do that too. Check the below code
img = np.array(Image.open('emma_stone.jpg'))
img0 = np.array(Image.open('mountains.jpg').resize(img.shape[1::-1])) # resize takes 2 arguments (WIDTH, HEIGHT)
print(img.dtype)
# uint8
dst = (img * 0.6 + img0 * 0.4).astype(np.uint8) # Blending them in
plt.figure(figsize=(10, 10))
plt.imshow(dst)
Check the below code for masking an image.
img = np.array(Image.open('emma_stone.jpg'))
ones = np.ones((img.shape[0] // 2, img.shape[1] // 2, 3))
zeros = np.zeros(((img.shape[0] // 4, img.shape[1] // 4, 3)))
zeros_mid = np.zeros(((img.shape[0] // 2, img.shape[1] // 4, 3)))
up = np.concatenate((zeros, zeros, zeros, zeros), axis=1)
middle = np.concatenate((zeros_mid, ones, zeros_mid), axis=1)
down = np.concatenate((zeros, zeros, zeros, zeros), axis=1)
mask = np.concatenate((up, middle, down), axis=0)
mask = mask / 255
img0 = mask * img
fig = plt.figure(figsize=(10, 10))
fig.add_subplot(1, 2, 1)
plt.imshow(img)
fig.add_subplot(1, 2, 2)
plt.imshow(img0)
Let’s draw the histogram using a matplotlib hist() function. Check the below code to draw the Pixel Intensity Histogram
img = np.array(Image.open('emma_stone.jpg'))
img_flat = img.flatten()
plt.hist(img_flat, bins=200, range=[0, 256])
plt.title("Number of pixels in each intensity value")
plt.xlabel("Intensity")
plt.ylabel("Number of pixels")
plt.show()
So in this article, we had a detailed discussion on Image Processing Using Numpy. Hope you learn something from this blog and it will help you in the future. Thanks for reading and your patience. Good luck!
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.
These graph chart and pictures are really good. I'm impressed to see it. When will you show more?
Picture is so beautiful. Will you upload more?