×

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images.

Imread is an Image reading library.

One of the most helpful and often used functions in the OpenCV-Python package is imread(). It is used to import a picture from the provided file into the Python program. After successfully loading the image, numpy.ndarray (NumPy N-dimensional array) is returned. When a colored image is loaded, this numpy.ndarray is a 3-Dimensional array; when a grayscale image is loaded, it is a 2-Dimensional array.

We are aware that Mahotas-imread is a straightforward module with a few operations. These operations are given below:

Let’s understand these operations one by one.

  1. Imread
    The picture file is read using this function.
  2. Imread_multi
    This function is used to read a multi-image image file. Currently, this function is supported by TIFF and STK (a TIFF sub-based format).
  3. Imsave
    Using this function, an image file can be written.

After the introduction, let’s move on to the importing part means Importing the opencv module to use the imread() method given below.

Importing opencv Module to Use imread() Method

In Python, we can't directly use the imread() method. To use the imread() method, we need to import the opencv-python library. So first, we need to install the opencv-python library.

To install the opencv library, we can use the below command.

# Installing the opencv-python library
pip install opencv-python

After installing the opencv-python library, we must import the opencv library into the python file. To import it, we can follow the below way.

# Importing the cv2 module
import cv2

Let’s understand about what is the syntax of the imread function given below:

Syntax of imread Function

The syntax of the imread() function is given below

cv2.imread(filename, flag)

Here we can see that the imread() function has 2 parameters filename and flag. Let’s understand them one by one.

filename: It is a compulsory parameter of the imread() function. The filename parameter can have the value path of the image file or image file name with the image extension.

If the image file is not in the working directory, then we need to pass the full path of the image file.

flag: The second parameter of the imread() function is the flag. It decides the mode to read the image file. It can have three values cv2.IMREAD_COLOR, cv2.IMREAD_GRAYSCALE, and cv2.IMREAD_UNCHANGED. The default value is cv2.IMREAD_COLOR.

Now let’s understand the type of returned object of the imread() function.

Return type: The imread function returns the ndarry if the image file is read successfully. Suppose the mode of reading is cv2.IMREAD_COLOR returns the 3d array if the mode of reading is cv2.IMREAD_GRAYSCALE then returns the 2d array. If the imread function cannot read the image file for any reason, it returns an empty matrix.

Let’s understand that the imread() function supports a variety of image formats, as given below.

Python's imread() Function Supports a Variety of Image Formats

The image formats that the cv2.imread() function supports many image formats, they  are as follows:

  • *.webp - WebP –
  • *.sr, *.ras - Sun rasters
  • *.exr - OpenEXR Image files
  • *.tiff, *.tif - TIFF files –
  •  *.hdr, *.pic - Radiance HDR
  • *.png - Portable Network Graphics
  •  *.pbm, *.pgm, *.ppm *.pxm, *.pnm - Portable image format
  •  *.bmp - Windows bitmaps
  • *.jpeg, *.jpg, *.jpe - JPEG files

So these are the image formats that the cv2.imread() function supports.

Note: The version of the OpenCV library installed on the system, platform, or environment (such as x86/ARM) determines the reading of images in the the.JPEG format. The most crucial aspect is the content of the numpy. ndarray returned by the cv2.imread() method, not the image file extension, determines the type of picture.

Loading an Image Using the imread() Function where flag =  cv2.IMREAD_COLOR

It serves as the flag parameter's default value. The number 1 corresponds to the numeric parameter cv2.IMREAD_COLOR. In addition, we can substitute 1 for cv2.IMREAD_COLOR.

The image is first converted to a three-channel BGR color image without a transparency channel when the flag with the value cv2.IMREAD_COLOR is supplied, and then the image is imported into the program.

To obtain the image's shape, we are utilizing the.shape method.

The number of rows, columns, and channels is returned as a tuple.

Example

import cv2


image = cv2.imread( "testImage.jpg", cv2.IMREAD_COLOR )
print( 'the dimensions of the image :', image.shape )

Output

The dimensions of the image: (1867, 2800, 3)

The result tuple contains three values: 3 for the number of channels, 2800 for the number of columns, and 1867 for the number of rows (height of the image) in the sample image.

As the flag value, in this case, is cv2.IMREAD COLOR, the loaded picture only has three channels blue, green, and red.

Even if the transparency or alpha channel is present in the sample image, it is not taken into consideration.

Loading an Image Using the imread() Function where flag =  cv2.IMREAD_GRAYSCALE

The image is first transformed to a single-channel grayscale image and then loaded into the application when the flag is passed with the value cv2.IMREAD_GRAYSCALE. Since cv2.IMREAD_GRAYSCALE corresponds to the integer value 0, and we can substitute 0 for it.

Example 1

import cv2


image = cv2.imread( "testImage.jpg", cv2.IMREAD_GRAYSCALE )
print( 'the dimensions of the image :', image.shape )

Output

The dimensions of the image: ( 1867, 2800 )

There are just two values in the output tuple. In the sample image, there are 2800 columns and 1867 rows. When the flag value is either 0 or cv2.IMREAD_GRAYSCALE, the image will be loaded as a grayscale image regardless of the input sample image supplied to the cv2.imread() method.

Example 2

import cv2


image = cv2.imread( "testPngImage.png", cv2.IMREAD_GRAYSCALE )
print( 'the dimensions of the image :', image.shape )

Output

The dimensions of the image: (566, 850)

Loading an Image Using the imread() Function where flag =  cv2.IMREAD_UNCHANGED

The picture and any alpha or transparency channels, if present, are loaded into the application when the flag with the value cv2.IMREAD_UNCHANGED is passed. You can substitute -1 for cv2.IMREAD_UNCHANGED since -1 is the integer value that corresponds to that constant.

Let’s understand it by taking an example is given below:

Example 1

import cv2


image = cv2.imread( "testImage.jpg", cv2IMREAD_UNCHANGED )
print(  'the dimensions of the image :', image.shape )

Output

The dimensions of the image: ( 1867, 2800, 4 )

Three values make up the output tuple. The sample image has 1867 rows, which corresponds to the height of the image. The width of the image is 2800 columns wide, and there are 4 channels in total.

As the flag value, in this case, is cv2.IMREAD_UNCHANGED, the loaded image has four channels: Blue, Green, Red, and Transparency. If the example image has the fourth channel, sometimes known as the transparency or alpha channel, it will be used.

Example 2

import cv2


image = cv2.imread( "testPngImage.png", cv2.IMREAD_UNCHANGED )
print(  'the dimensions of the image :', image.shape )

Output

The dimensions of the image: ( 566, 850, 4 )

Three values make up the output tuple. The sample image has 1867 rows, which corresponds to the height of the image. The width of the image is 2800 columns wide, and there are 4 channels in total.

As the flag value, in this case, is cv2.IMREAD_UNCHANGED, the loaded image has four channels: Blue, Green, Red, and Transparency. If the example image has the fourth channel, sometimes known as the transparency or alpha channel, it will be used.

imread() and Color Channels

The image is decoded using the imread() function into a matrix, with the color channels saved in the following order: blue, green, red, and A (Transparency).

If (400, 640, 4) is the shape of the image, then

(:, :, 0) represents Blue channel
(:, :, 1) represents Green channel
(:, :, 2) represents Red channel
(:, :, 3) represents Transparency channel

Conclusion

You have learned various methods for loading an image in this tutorial simply by changing the value of the flag parameter. We learned how to read an image into a Python array using the cv2 imread() method. Just keep in mind two things: if the sample picture file isn't already in your current working directory, you must supply its entire path, and you can also pass the integer values [1, 0, & -1] to the flag parameters for [cv2.IMREAD COLOR, cv2.IMREAD GRAYSCALE, & cv2.IMREAD UNCHANGED].

Numerous image file types may be read and written by OpenCV with ease (e.g., JPG, PNG, TIFF). The library also makes it easier to interact with the opened window and display a picture on the screen.

Since the cv2.imread function fails and returns a NoneType Python object, you should carefully check the input filename if an image cannot be read by OpenCV. If the file does not exist or if OpenCV does not accept the image format, the function will fail.

Based on the values of the underlying NumPy array form, we have additionally written the image dimensions (width, height, and number of channels) to the terminal.


Related Topics

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

Python Image Processing

What is an Image? Images are the pictures that will define the world, and it has their own story, and consists of information about them and these are useful in many...

9 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Yield vs Return in Python

In this article, you will learn about " Yield " and " Return " in Python. You will also understand the difference between " Yield " and " Return "...

6 minutes read.

Python program to check whether a given number is prime or not

Python program to check whether a given number is prime or not A positive integer greater than 1 is called a prime number if it is divisible by one and number...

1 minute read.

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of...

7 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Exrex Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster...

4 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

OSError in 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...

4 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute 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.

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

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

How to plot a Histogram in Python

A Histogram is used to represent a given data provided as a chunk. This histogram is a graphical representation that uses bars to indicate the ranges of the data. In...

4 minutes read.

List Index out of Range Python for Loop

The List is generally used in Python to store multiple items or elements inside one single variable. The List is ordered in nature, the List can contain the elements inside...

3 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.