×

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into NumPy arrays structure in height and channel format.

We need to import two different modules for this process and those are to be followed by:

  • NumPy
  • Pillow

NumPy:

NumPy by default was brought up from the versions 3.x, NumPy comes with the Python wholly but if it is not present, we can install it from cmd by using the command:

pip install NumPy

This works with the arrays and has functions for image classification too.

Pillow:

Pillow is an image editor tool which is been explicitly installed in the new versions of Python. In the Python version Python3, the library pillow is just nothing but an advanced and upgraded version of PIL. If it is not present in the main idle, we can install by using the command:

pip install pillow

As the versions of the pillow are not up to date if we want to check the version of pillow, we jus need to use the command

Import PIL
Print (‘Installed pillow version:’, PIL. __version__)

The first step is to load image by using the path directory assigning to it and importing the image which is of PNG format. We need to focus on the image class because it is the main source of PIL. OPEN() function is used to display up image and load the digital content in it and retrieve the data as of pixel format.

Image to NumPy Arrays in Python

Sample image is imported using the code below.

Code:

From PIL import Image
#sample.png is the name of the image that we have uploaded in the current directory or we need
#To give the path
Image=Image. Open(‘Sample.png’)
#
PNG
(300, 150)
RGB

After importing the image we need to convert the image into NumPy array and Python contains many modules and they contain API which is used to convert the image to NumPy array.

Python NumPy module in itself provides and it contains the methods and they are followed as:

  • asarray()
  • NumPy. Array ()
  • Image.fromarray()

Using asarray():

It is a function that is implemented to convert PIL images into NumPy arrays module. This function is used converts the given input to an array. Array makes a duplicate copy of the input we given but the asarray will not make the copy until its unnecessary.

Code:

#Import the necessary libraries
From PIL import Image
From NumPy import asarray
#Loading the given image and converting to numpy array
Image = Image. Open(‘Sample.png’)
#Asarray () function is used to load and convert PIL images into NumPy arrays respectively
NumPy data = asarray(image)
#<class ‘NumPy. Nd array’>
Print (type (NumPy data))
#Shape
Print (NumPy data. shape)

Output:

<class ‘numpy.ndarray’>
(200, 400, 3)
Using NumPy. Array ():

NumPy array function is used to create arrays in Python by manipulating Python structures like lists and tuples into arrays or by using intrinsic NumPy creation in Python.

And the second stage of deployment of code:

from PIL import Image
Import NumPy
Image = Image. Open(“Sample.png”)
np_image = NumPy. Array(img)
print(np_image.shape)

Output:

(200, 400, 3)

Image.fromarray():

from array function is implemented to make image memory form an image object which exports the array by providing the required path and file name respectively.

Code:

import numpy as np
from PIL import image
Array = np.arrange(0, 73280, 1, np.uint8)
Array = np.reshape(array, (1024, 720))
im = Image.fromarray(array)
im.save(“filename.jpeg”)

We can use the function imageio. imwrite () function to save NumPy arrays as an image and  we can also deploy the SciPy and matplotlib modules to implement the images to numpy array.

We can also convert NumPy array to back its image.

The image.fromarray() function is used to convert the image to array and comes with the handmade manipulation functions and numpy.ndarray image data.

from PIL import Image
from numpy import asarray
#Load the image
Image=Image. open(‘Kolkata.jpeg’)
#Converting the image into numpy array
data = asarray(image)
Print(type(data))
#shape resizing
Print (data. Shape)
#creating pillow image
Image2=Image.fromarray(data)
Print(type(image2))
#concludimg the details
Print (image2.mode)
Print (image2.size)

Output:

<class ‘numpy. ndarray’>
(450,800,3)
<class ‘PIL.Image.Image’>
RGB
(800,450)

Related Topics

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Gethostbyname() function in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Working with files in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has an...

5 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Python logging Module

Python logging Module Introduction By logging word we understand the tracking of the events which happens when we run some software. Logging process is very important part for developing software, debugging...

12 minutes read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.

Python Project Ideas for Beginners

Python project ideas for beginners Advanced Python is an amazing platform to grow and achieve success as a developer in the future. Python is a programming language that can be very...

7 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python MongoDB Tutorial

An Introduction to MongoDB MongoDB is a document-oriented database application. It is an Open-source and platform-independent program. MongoDB is similar to few NoSQL databases that store the data in the documents...

17 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

Adding item to a python dictionary

The dictionary is one of python’s built-in data structures where it stores key-value pairs. A dictionary is a collection of ordered values that can be changeable. We can add, modify,...

3 minutes read.

Kite Python

Kite in Python: The Kite is a package provided by the python programming language; it works with the help of artificial intelligence and helps us write code inside the visual studio....

3 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Traverse Dictionary in Python

Traversing a dictionary is visiting each and every step in the dictionary, which is also called iterating the dictionary In Python, dictionaries are a useful and commonly used data structure in...

3 minutes read.

Python math.cos and math.acos function

Math.cos() function In Python, the Math module is used for performing the mathematical operations. It includes the math.cos() function that is used for obtaining the cosine value of an angle in...

3 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.