How to Load an Image in Python

Spread the love

In this post you will learn how to load an image in python using OpenCV library.

Load an Image –

To load an image we will use the OpenCV library. So first you have to install the openCV library.

Install OpenCV Using Pip –

pip install opencv-python

Install OpenCV using Anaconda –

conda install -c conda-forge opencv

How to load a Grayscale Image in python-

To load an image in OpenCV, we use the imread method.

# import libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt

# load a grayscale image
image = cv2.imread("maldives.jpg", cv2.IMREAD_GRAYSCALE)

# show image
plt.imshow(image, cmap='gray')
plt.axis("off")
plt.show()

And if you print the image you will see that under the hood it’s a numpy array.

# show image data
image

output - 
array([[137, 137, 138, ..., 108, 107, 107],
       [137, 138, 138, ..., 108, 107, 107],
       [138, 138, 138, ..., 108, 108, 108],
       ...,
       [219, 218, 218, ..., 166, 165, 172],
       [217, 216, 217, ..., 159, 162, 183],
       [217, 216, 218, ..., 150, 139, 158]], dtype=uint8)

And shape of the data is

# show shape
image.shape
output - 
(669, 1000)

Each number in the numpy array is an image’s pixel intensity. In gray scale image pixel intensity value ranges from 0 (black) to 255 (white).

How to load a Color Image in Python –

# load a color image
image = cv2.imread('maldives.jpg', cv2.IMREAD_COLOR)
# show the image
plt.imshow(image)
plt.axis("off")
plt.show()
# show image data
image

truncated output - 
array([[[210, 148,  88],
        [210, 148,  88],
        [211, 149,  89],
        ...,
        [190, 117,  59],
        [189, 116,  58],
        [189, 116,  58]],

       [[210, 148,  88],
        [211, 149,  89],
        [211, 149,  89],
        ...,
        [190, 117,  59],
        [189, 116,  58],
        [189, 116,  58]],

       [[211, 149,  89],
        [211, 149,  89],
        [211, 149,  89],
        ...,
        [190, 117,  59],
        [190, 117,  59],
        [190, 117,  59]],

       ...,

A color image is made of Red, Green and Blue (RGB) intensity. But By default OpenCV read them in Blue, Green, Red (BGR).

To convert BGR to RGB, you have to write

# convert to RGB
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# show image
plt.imshow(image)
plt.axis("off")
plt.show()

Rating: 1 out of 5.

Leave a Reply