×

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 Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Append key Value to Dictionary in Python

The Python dictionary is one of the built-in data types. Elements of dictionaries are key-value pairs. In Python, there are numerous ways to add dictionaries. Let's examine some of the...

9 minutes read.

Difference between Yield and Return in Python

Python yield statement The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns...

3 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Cursor in Python

The cursor is an item that aids in query execution and records retrieval from databases. The cursor is crucial to the execution of the query. In-depth information on the execution...

7 minutes read.

What Does the Percent Sign (%) Mean in Python?

In python, the percent sign is called modulo operator " %, " which returns the rest of partitioning the left-hand operand by the right-hand operand. Example: value1 = 8 value2 = 2 remainder =...

4 minutes read.

Python Simple Interest

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

3 minutes read.

Python Printf Style Formating

String objects have one special implicit activity: the % administrator (modulo). This is otherwise called the string designing or interjection administrator. Given design % values (where configuration is a string),...

3 minutes read.

How to check data type in python

The data type represents the nature of a variable; it determines what kind of data it can store and what operations can be carried out on it. There are five...

4 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

How To Install Python In Ubuntu

How To Install Python In Ubuntu Ubuntu is free and open-source software and it is an essential part of the Linux distribution. It is a popular operating system developed by Canonical. If we...

3 minutes read.

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python History

Python is one of the top trending, widely-used programming languages. Python is a general-purpose programming language. Python language is known for its features. Some features are given below: SimplisticFree and open...

4 minutes read.

Python String Lowercase

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

3 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

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.

Reverse a Number in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

4 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

List in Python

What is List in Python In Python, lists are used to store the multiple values in one variable. We can say that list is the collection of similar as well as...

3 minutes read.

How to print in the same line in Python?

How to print in the same line in python By default, the print function in Python takes us to the next line and prints the desired statement in the output. In this...

5 minutes read.