Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
cv2.imread() in OpenCV
2.1.
Syntax
2.2.
Parameter
2.3.
Return Value
3.
Example of OpenCV cv2.imread() Method
3.1.
Reading color image using imread() Method
3.2.
Python
3.3.
Reading image as greyscale using imread() Method
3.4.
Python
3.5.
Reading image with transparency channel using imread() Method
3.6.
Python
3.7.
OpenCV cv2.imread() and Color Channels
4.
Exception of OpenCV cv2.imread() Method
5.
Frequently Asked Questions
5.1.
What is the purpose of the flags parameter in cv2.imread()?
5.2.
How should exceptions be handled when using cv2.imread()?
5.3.
What are some common preprocessing steps after loading images with cv2.imread()?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

OpenCV cv2.imread()

Author Ayush Mishra
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

OpenCV stands for  Open Source Computer Vision Library. It is a practical open-source toolkit created to help programmers and academics create programs that analyze photos and videos, from straightforward operations like reading and displaying images to complex ones like object detection and facial recognition.

OpenCV cv2.imread()

In this blog, we will discuss the OpenCV cv2.imread() function in Python. Let’s start going!

cv2.imread() in OpenCV

The OpenCV cv2.imread() function is used to read an image file from the given directory and return a NumPy array containing the pixel values for the picture. The OpenCV library's other functions and resources can process, analyze, or edit this NumPy array.

Syntax

The basic syntax of cv2.imread() is:-

import cv2

image = cv2.imread(filename, flag)

Parameter

The parameter of cv2.imread() are:-

  • filename: The path to the image file you want to load is specified by this option. The path to your filesystem's image file can be absolute or relative.
     
  • flags: The flags argument is an optional parameter that specifies how the picture should be loaded and read. It establishes the loaded image's color space and channel settings. It is an integer with a range of specified constants that it can accept. Some basic flags include are:-

    • cv2.IMREAD_COLOR: This default flag loads the image in the BGR color format. It is the same as passing the value of the flag as 1.
       
    • cv2.IMREAD_GRAYSCALE: This flag loads the image in grayscale. It is the same as supplying the value 0 for the flag.
       
    • cv2.IMREAD_UNCHANGED: If an alpha channel is present, the image is loaded exactly as it is with this flag set. It is the same as setting the flag value to -1.

Return Value

An OpenCV cv2.imread() method returns a NumPy array representing the loaded picture. Some important points regarding return value are:-

  • If we use the cv2.IMREAD_COLOR flag, the function will return a 3D NumPy array that represents a color image. The array will have the following dimensions: height, breadth, and channels.
     
  • If the cv2.IMREAD_GRAYSCALE parameter is used, and a 2D NumPy array depicting a grayscale image will be returned. The array's dimensions are (height, width).
     
  • If the cv2.IMREAD_UNCHANGED flag is used; the function will return a 3D NumPy array with the original image's color channels and any alpha channels that may have been present. The array will have the following dimensions: height, breadth, and channels.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example of OpenCV cv2.imread() Method

In this section, we will see examples to understand Python's cv2.imread() method.

Reading color image using imread() Method

The default method used to read a color image is cv2.IMREAD_COLOR. The BGR (Blue-Green-Red) color format is read from the image.

  • Python

Python

import cv2
#reading image
image= cv2.imread('./cat.jpg')
#printing its shape
print('Image Dimensions :', image.shape)


#Displaying Image
cv2.imshow("Image", img)

cv2.waitKey(0)
# Closing all windows

cv2.destroyAllWindows()


Output

Output
Output

Explanation

The (height, width, number_of_channels) tuple returned by img.shape. The image consists of three color channels with a 225-pixel height and 224-pixel width. The cv2.imshow() will display the image.

Reading image as greyscale using imread() Method

The input image can be used as color or grayscale images. If the flag argument is cv2.IMREAD GRAYSCALE reads the image in a grayscale image.

  • Python

Python

import cv2

img = cv2.imread('./cat.jpg', cv2.IMREAD_GRAYSCALE)

print('Image Dimensions:', img.shape)

#Displaying Image

cv2.imshow("Image", img)

cv2.waitKey(0)

# Closing all windows

cv2.destroyAllWindows()


Output

Output
Output

Explanation

The (height, width, number_of_channels) tuple returned by img.shape. The image consists of a 225-pixel height and 224-pixel width. The cv2.imshow() will display the grey image.

Reading image with transparency channel using imread() Method

The cv2.IMREAD_UNCHANGED method is used to read an image with an alpha channel. The image is read in BGR color format.

  • Python

Python

import cv2

img = cv2.imread('./cat.jpg', cv2.IMREAD_UNCHANGED)

print('Image Dimensions :', img.shape)

#Displaying Image

cv2.imshow("Image", img)

cv2.waitKey(0)

# Closing all windows

cv2.destroyAllWindows()


Output

Output
Output

Explanation

The (height, width, number_of_channels) tuple returned by img.shape. The image consists of a 225-pixel height and 224-pixel width. The cv2.imshow() will display the image.

OpenCV cv2.imread() and Color Channels

The  imread() function decodes the image into a matrix, with the color channels saved in the following order: blue, green, red, and transparency.

# Get blue channel
r1 = image[:,:,0]
# Get green channel
g1 = image[:,:,1] 
# Get red channel
b1 = image[:,:,2] 

Exception of OpenCV cv2.imread() Method

Some exceptions of OpenCV cv2.imread() Method are:-

  • You may have a "File not found" error if the image file location provided is wrong, or the file doesn't exist. A try and except block can handle this and capture the FileNotFoundError.
     
  • OpenCV may throw an exception if you try to load an image in an unsupported format. You can manage this by catching the cv2.error exception.
     
  • A MemoryError may appear if you try to load a picture more significant than your available memory. You can handle this by catching the MemoryError.
     
  • The cv2.imread() method will throw a "UnicodeError" exception if the supplied file path contains non-ASCII characters or is too long.
     
  • If the supplied file is encrypted or password-protected, the cv2.imread() method will throw a "cv2.error" exception.

Frequently Asked Questions

What is the purpose of the flags parameter in cv2.imread()?

The flags parameter controls how the image should be loaded. It establishes the loaded image's color space and channel settings.  To describe how the picture should be loaded, you can use predefined flags like cv2.IMREAD_COLOR,  cv2.IMREAD_GRAYSCALE, and cv2.IMREAD_UNCHANGED.

How should exceptions be handled when using cv2.imread()?

Try and except blocks can handle errors thrown by cv2.imread(). This enables one to respond appropriately to failures, display illuminating notifications, and handle them graciously.

What are some common preprocessing steps after loading images with cv2.imread()?

Typical preprocessing procedures after loading images include scaling, normalization, noise reduction, and conversion to alternative color spaces as required for specific image processing or analytic jobs.

Conclusion

The OpenCV cv2.imread() method is essential for loading and reading pictures in various formats. Developers and researchers can efficiently load and modify images to support a variety of computer vision tasks by understanding their specifications, color channel options, and best practices.

We hope this blog has helped you to gain knowledge of OpenCV cv2.imread(). Do not stop learning! We recommend you read some of our related articles to OpenCV : 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. For placement preparations, you must look at the problemsinterview experiences, and interview bundles.

We wish you Good Luck! 

Happy Learning!

Previous article
OpenCV cv2.imwrite() Method
Next article
Image Read-Write-Display in OpenCV
Live masterclass