×

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

How to change a value of a tuple in Python

Python is the language for newly evolving technologies and has become one of the most popular programming languages in the world. It is used in everything right, from simple algorithm...

3 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Add Element to Tuple in Python

Python: Popular high-level, all-purpose programming language Python. The new version of the Python programming language, Python 3, is used for all software applications, including web development. Python is the best programming...

4 minutes read.

Data Class in Python

Introduction In Python 3.7, the dataclass modules are introduced as a practical tool for creating organized classes designed specifically for data storage. These classes contain specific attributes and capabilities to deal...

6 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

Python abs() function

Python abs() function The abs() function returns the absolute value of a number. Syntax abs(x) Parameter x: The parameter ‘x’ can be an integer value, a floating point number or a complex number. Return This function returns...

1 minute read.

Python Interpreter

In this tutorial, we will go through the basic knowledge about what an interpreter is and how we use it in the python programming language. It is one of the...

3 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Python Set issubset() method

Python Set issubset() method The set.issubset() method in Python returns True if all items in the set exists in the specified set, otherwise it returns False. Syntax set.issubset(set1) Parameter set- This parameter represents the set to check whether...

2 minutes read.

Reverse a String 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...

4 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

XXhash Python

Python: 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 is said...

6 minutes read.

Cross Validation in Sklearn

Data scientists can benefit from cross-validation in machine learning in two key ways: it can assist in minimising the amount of data needed and ensure the artificial intelligence model is...

14 minutes read.