Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Image Processing with SciPy and NumPy in Python
Next article icon

Image Processing with SciPy and NumPy in Python

Last Updated : 12 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this tutorial, we will discuss Image Processing in Python using the core scientific modules like NumPy and SciPy. The images are made up of NumPy ndarrays so we can process and manipulate images and SciPy provides the submodule scipy.ndimage that provides functions that can operate on the NumPy arrays.

Image Processing with SciPy and NumPy in Python

 We will discuss how to open and write to images, and will also cover different manipulation and filtering techniques. So before getting started let's see how to install both modules.

Installation

Numpy: To install numpy type the below command in the terminal.

pip install numpy

Installing Numpy on Linux using PIP

SciPy: You can use the above command to install SciPy as well.

pip install scipy

pip install scipy

Opening and Writing Images

The misc package of SciPy comes with some preloaded images. We will use those images to learn about image processing. One such image is provided by the face() function. The face() function will get a colored image of a raccoon face.

Example: Saving image using SciPy

Python3
from scipy import misc import imageio import matplotlib.pyplot as plt  # reads a raccoon face face = misc.face()  # save the image imageio.imsave('raccoon.png', face)  plt.imshow(face) plt.show() 

Output:

scipy open image

Example: Creating NumPy array from the image

Here we will read the image using the imread() function.

Python3
from scipy import misc import imageio import matplotlib.pyplot as plt  img = imageio.imread('raccoon.png')  print(img.shape) print(img.dtype)  plt.imshow(img) plt.show() 

Output:

(768, 1024, 3) uint8

imread image scipy

Creating RAW file

A RAW file is a file containing minimally processed data from an image sensor. We can create this file using the tofile() method of the scipy package.

Example: Creating RAW file using SciPy

Python3
from scipy import misc import imageio import matplotlib.pyplot as plt  # reads a raccoon face face = misc.face()  face.tofile("raccoon.raw") 

This will create a .raw file in our current working directory.

Opening RAW File

For opening .raw file we will be needing the NumPy module that will use the fromfile() method. This function is an efficient way of reading binary data with known data type as well as parsing simply formatted text.

Example: Reading from RAW file using NumPy

Python3
import numpy as np  img = np.fromfile('raccoon.raw',                    dtype=np.uint8)  print(img.shape) 

Output:

(2359296,)

Getting Statistical Information

We can use the max() and min() functions to get the maximum and minimum along the given axis. And to find the mean we can use the mean() function.

Example: Getting min, max, and mean values

Python3
from scipy import misc  img = misc.face()  print(img.max()) print(img.min()) print(img.mean()) 

Output:

255 0 110.16274388631184

Cropping Image

As we know that images are represented by numbers in a matrix, so changing the value of the matrix will result in changing the original image. Let's see how to use this idea for cropping the image.

Example: Cropping the image

Python3
from scipy import misc import matplotlib.pyplot as plt  # for grascaling the image img = misc.face(gray = True)   x, y = img.shape  # Cropping the image crop = img[x//3: - x//8, y//3: - y//8]  plt.imshow(crop) plt.show() 

Output:

cropping image scipy and numpy

Flipping Images

We can use the flipud() function of the numpy module to flip that image. This function flips the array(entries in each column) in up-down direction, shape preserved.

Example: Flip Image using Scipy

Python3
from scipy import misc import numpy as np import matplotlib.pyplot as plt  img = misc.face()  flip = np.flipud(img)  plt.imshow(flip) plt.show() 

Output:

flip image using numpy and scipy

Rotating Images

To rotate the images we can use the ndarray.rotate() function. This function rotates the image at a specific angle.

Example: Rotate Image using SciPy and NumPy

Python3
from scipy import misc,ndimage import matplotlib.pyplot as plt   img = misc.face()  rotate = ndimage.rotate(face, 30)  plt.imshow(rotate) plt.show() 

Output:

rotate image using numpy and scipy

Filtering Images

In simpler terms image filtering is a process for enhancing or modifying an image where we can increase sharpness, enhance edges, or blurs the image. In Image filtering, some algorithm is applied to the pixel value of the given image and that algorithm determines the value of the output image. Let's see some image filtering operations that can be done using NumPy and SciPy.

Blurring Images

Blurring an image is a process of reducing the level of noise in the image. For this, we can either use a Gaussian filter or a unicorn filter.

Example: Blur Images using SciPy and NumPy

Python3
from scipy import misc,ndimage import matplotlib.pyplot as plt  img = misc.face()  blur_G = ndimage.gaussian_filter(img,sigma=7)  plt.imshow(blur_G) plt.show() 

Output:

blur images using scipy and numpy

Sharpening Images

Sharpening refers to increase contrast b/w light and dark regions and make the image more defined and brings out image features. There are three main reasons to sharpen your image: to overcome blurring introduced by camera equipment, to draw attention to certain areas, and to increase legibility. If blurry text is present in the image it becomes easy to read.

Example: Sharpening images using NumPy and SciPy

Python3
from scipy import misc, ndimage import matplotlib.pyplot as plt  img = misc.face(gray=True).astype(float) blur = ndimage.gaussian_filter(img, 5)  # Showing Blur Image plt.imshow(blur) plt.show()  blur_G = ndimage.gaussian_filter(blur, 1) alpha = 30 sharp = blur+alpha*(blur-blur_G)  # showing sharp images plt.imshow(sharp) plt.show() 

Output:

Sharpening images using NumPy and SciPy

Denoising Images

Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. At first, let's create a noisy image - 

Example 1: Creating a noisy image

Python3
from scipy import misc,ndimage import matplotlib.pyplot as plt import numpy as np  img=misc.face(gray=True).astype(float) img=img[40:100,30:100]  noise_img=img+0.9*img.std()*np.random.random(img.shape)  plt.imshow(noise_img) plt.show() 

Output:

noisy image using scipy and numpy

To smooth the edges and the noise we use the Gaussian filter.

Python3
denoised = ndimage.gaussian_filter(noise_img, 2.2)  plt.imshow(denoised) plt.show() 

Output:

denoise gaussian filter

We can also preserve the edges using the median filter.

Python3
denoised = ndimage.median_filter(noise_img, 4)  plt.imshow(denoised) plt.show() 

Output:

denoised scipy and numpy

Edge Detection

The process of image detection involves detecting edges in the image. It works by detecting discontinuities in the brightness. For high-intensity variations, we can use Sobel, a gradient operator-

Example: Edge detection using SciPy and NumPy

Python3
from scipy import misc, ndimage import matplotlib.pyplot as plt import numpy as np  img = np.zeros((300, 300)) img[64:-64, 64:-64] = 1 img = ndimage.rotate(im, 30, mode='constant') img = ndimage.gaussian_filter(im, 7)  # Original image plt.imshow(im) plt.show()  # edge detection x = ndimage.sobel(im, axis=0, mode='constant') y = ndimage.sobel(im, axis=1, mode='constant') Sobel = np.hypot(x, y)  plt.imshow(sob) plt.show() 

Output:

edge detection scipy and numpy


Next Article
Image Processing with SciPy and NumPy in Python

A

abhishek1
Improve
Article Tags :
  • Python
  • Image-Processing
Practice Tags :
  • python

Similar Reads

    Image processing with Scikit-image in Python
    scikit-image is an image processing Python package that works with NumPy arrays which is a collection of algorithms for image processing. Let's discuss how to deal with images in set of information and its application in the real world. Important features of scikit-image : Simple and efficient tools
    2 min read
    Multidimensional image processing using Scipy in Python
    SciPy is a Python library used for scientific and technical computing. It is built on top of NumPy, a library for efficient numerical computing, and provides many functions for working with arrays, numerical optimization, signal processing, and other common tasks in scientific computing. Image proce
    14 min read
    Create a white image using NumPy in Python
    Let us see how to create a white image using NumPy and cv2. A white image has all its pixels as 255. Method 1: Using np.full() method :   Python3 # importing the libraries import cv2 import numpy as np # creating an array using np.full # 255 is code for white color array_created = np.full((500, 500,
    1 min read
    Top Python libraries for image processing
    Python has become popular in various tech fields and image processing is one of them. This is all because of a vast collection of libraries that can provide a wide range of tools and functionalities for manipulating, analyzing, and enhancing images. Whether someone is a developer working on image ap
    8 min read
    SunPy | Plotting a Solar Image in Python
    SunPy is a package for solar data analysis using Python. We will be using this package for analysis of solar data Installation On the command line type: pip install sunpy Downloading Sample Data The SunPy package contains a number of data files which are solar data of proton/electron fluxes from var
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences