×

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 Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Num2words

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

3 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

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

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 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 Identifiers

Identifiers in Python User-defined names are identifiers in Python that are used to name variables, functions, classes, modules, and other things. You can create Python identifiers using these rules: As an identifier...

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

Python Memory Management

In order to manage memory, Python uses a private heap that contains all of its data structures and objects. The Python memory manager is responsible for the internal management of...

11 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

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