VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/05/image-processing-using-numpy-with-practical-implementation-and-code/

⇱ Numpy for image processing | Image Processing With Numpy


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Reading list

Image Processing Using Numpy: With Practical Implementation And Code

Akshay Last Updated : 28 Sep, 2024
7 min read

Introduction

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.

πŸ‘ Image Processing Using Numpy 1

Installation of Required Libraries

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

Importing the Required Libraries

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

Opening an Image

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()

  • imread() – to read the images
  • imshow() – to display the images

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()

Details of an Image

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

# 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

πŸ‘ Image Processing Using Numpy 3

Check the below code to rotate an image by 90 degrees in an anticlockwise direction.

plt.imshow(np.rot90(img))

Output

πŸ‘ Image Processing Using Numpy 4

Negative of an Image

Converting a color image to a negative image is very simple. You to perform only 3 steps for each pixel of the image

  • First, get the RGB values of the pixel
  • Calculate new RGB values using R = 255 – R, G = 255 – G, B = 255- B
  • Finally, save the new RGB values in the pixel

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')
πŸ‘ Image Processing Using Numpy rgb image

Padding Black Spaces

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)
πŸ‘ padding black Image Processing Using Numpy

Visualizing RGB Channels

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)
πŸ‘ Visualizing RGB Channels

Colour Reduction

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)
πŸ‘ Colour Reduction

Trim Image

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')
πŸ‘ Trim Image

Pasting With Slice

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')
πŸ‘ Pasting With Slice

Binarize Image

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)
πŸ‘ Binarize Image

Flip Image

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)
πŸ‘ Flip Image

An Alternate way to Flip an Image

  • np.flipud() : [up/down]flips over x-axis
  • np.fliplr() : [left/right]flips over y_axis

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))
πŸ‘ An Alternate way to Flip an Image

Blending Two Images

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)
πŸ‘ Blending Two Images

Masking Images

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)
πŸ‘ Masking Images

Histogram For Pixel Intensity

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()
πŸ‘ Histogram For Pixel Intensity

Conclusion

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. 

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

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?

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner