OpenCV provides cv2.imread()
function to read images. This function accepts two arguments:
cv2.imread(imagepath, flag)
Note: If the image does not load, then cv2.imread()
function returns None
. You can use None in the if statement to check whether the image is loaded or not.
It is important to note that OpenCV supports the following image formats:
For a complete list of image formats supported by OpenCV, visit OpenCV Documentation.
There are various flags that you can pass to the imread()
function, but some of the commonly used flags are explained below:
cv2.IMREAD_COLOR: This flag reads the image in BGR mode, and it is the default flag.
Note: OpenCV reads the image in BGR mode, not in RGB mode. So, the order of the channels is blue, green, and red.
cv2.IMREAD_UNCHANGED: This flag reads the image as it is. This means if there is a PNG image, then it will be read as a BGRA image. Here, A refers to the alpha channel, which provides transparency to the image. Similarly, if an image is JPEG, then it will be read as a BGR image.
cv2.IMREAD_GRAYSCALE: It reads the image in grayscale color mode. This flag is generally used to convert a color image to grayscale.
Let's understand how to read an image in OpenCV Python with the help of examples.
Suppose you want to read a JPEG image, then run the below code:
import cv2 img = cv2.imread('/home/mohit/cardiff.jpg') if img is None: print('Image is not present') else: cv2.imshow(img) cv2.destroyAllWindows() cv2.waitKey(0)
Output
For better understanding, the code is explained line by line.
import cv2
Imports the OpenCV library into the program.
img = cv2.imread('/home/mohit/cardiff.jpeg')
The image is present in /home/mohit/cardiff.jpeg path, and the imread() function reads it in BGR mode.
if img is None: print('Image is not present')
It checks whether the image is read successfully or not.
cv2.imshow(img) cv2.destroyAllWindows() cv2.waitKey(0)
This code displays the image. If you want to run this code on Google Colaboratory, then you have to make two modifications:
cv2_imshow()
function by running the below code:from google.colab.patches import cv2_imshow
cv2.imshow()
function, use cv2_imshow(img)
function.The entire code for running on Google Colaboratory is shown below:
import cv2 from google.colab.patches import cv2_imshow img = cv2.imread('/content/cardiff.jpg') if img is None: print('Image is not present') else: cv2_imshow(img)
If you want to read the same image as grayscale, then pass cv2.IMREAD_GRAYSCALE flag to the cv2.imread() function.
import cv2 img = cv2.imread('/home/mohit/cardiff.jpg', cv2.IMREAD_GRAYSCALE) if img is None: print('Image is not present') else: cv2.imshow(img) cv2.destroyAllWindows() cv2.waitKey(0)
Output