OpenCV is a cross-platform library that allows you to develop compute vision applications. It can do many things like image processing, video capturing e.t.c. Using it you can make projects like face detection, object detection e.t.c. OpenCV has many functions that do all these tasks efficiently. The cv2 imread() function is one of them. It allows you to read any image. In this entire tutorial, you will know its implementation.
Most of the functions are built for processing images and videos. Let’s know the picture that I am using in the upcoming examples. And it is the below.
How to read image file using cv2 imread() method
To read the image using imread() method, you have to pass two parameters. One is the path of the image and the other is the flag, which is optional. The flag can be any one of the values from cv2.IMREAD_COLOR,cv2.IMREAD_COLOR and cv2.IMREAD_UNCHANGED. The flag cv2.IMREAD_COLOR is the default.
Let’s read the image using the cv2 imread() method.
import cv2 img = cv2.imread("flowers.jpg") print(img)
How to know image type in OpenCV
Now you have read the image using the cv2.imread(), let’s know the type of the image. To do so you will use the default python method type().
In the same way, you can also know the data type of the image using the img.dtype. Run the codes given below to know the type of the image.
print("Image type:",type(img)) print("Image Data Type: ",img.dtype)
You can see all the pixel values of the image are of a NumPy array type. And the maximum values of each pixel can be from 0 to 256 (2**8).
Know the shape of the image in OpenCV
The shape tells the dimensions of the image file you read. In OpenCV, you have to the img. shape to find the dimensions.
Here 425 is the number of columns, 640 is the number of rows and 3 is the number of channels. My image is colorful, that’s why the channel will be 3. For the gray image, it is 1.
Find the size of the image in OpenCV python
The above shape tells you the dimension of the image. If you use img.size then it will multiply all the values (425*640*3) you get in the img.shape.
Get length of the image in python using cv2 imread
You can also know the dimensions of the image file using len() method. For example, to know the total rows (height) you will use the len(img). In the same to know the total columns(width), use len(img). Lastly, to know the number of channels use len(img).
Run the following lines of code and see the output.
print("Rows or Height:",len(img)) print("Columns or Width:",len(img)) print("Number of channels:",len(img))
Reading the image file is a must for further processing of the image. These are the examples that will clear your understanding of how to read image file in python using the cv2 imread() method. Even you are finding difficulties in it then you can contact us for more help.
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.