×

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 GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python ascii() Function

Python ascii() Function The ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc). This function will replace any non-ascii characters with escape characters. Syntax ascii(object) Parameter object:  An object, like String, List, Tuple, Dictionary, etc. Return This...

1 minute read.

Python BytesIO

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

3 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 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.

How to Install Tweepy in Python

In this article, we will learn or understand how to install Tweepy in Python and what Tweepy is. Firstly, let’s understand What Tweepy is. As we all know, one of the...

3 minutes read.

Python Matrix Operations

Python Matrix In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using...

21 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

How to Write a Configuration file in Python

This article will discuss How to write a configuration file in python, why we need config files in Python, the format of the configuration file, file extensions, and how to...

11 minutes read.

ER diagram of the Bank Management System in python

What is an ER diagram? The full form of the ER diagram is the Entity Relationship diagram. This diagram is used in database management systems to have a rough idea of...

3 minutes read.

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Standard Scaler in SKLearn

The sci kit learns in python is a library thatch is used in machine learning which is used to work on data modeling.It is only focused on the data modeling,...

4 minutes read.

How to run Python program in CMD

How to run python program in cmd Command Prompt provides us all together with a different approach for dealing with our programs. The programs can be executed by accessing the directories. In...

3 minutes read.

Python Variables, Constants and Literals

Python is today's most valuable, easy-to-implement and sought-out programming language. Nowadays, developers want to focus on implementing the program rather than spending time with complex programs. So, for this reason,...

17 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Copying a file from one folder to Another with Python

In this article, we shall discuss copying a file from one folder to another using python functions. A file is a collection of data or information stored on a computer....

3 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.