Python OpenCV Read an Image to NumPy NdArray: A Beginner Guide – OpenCV Tutorial

By | October 14, 2020

OpenCV is a powerful tool to process images. In this tutorial, we will introduce how to read an image to numpy ndarray.

Python pillow library also can read an image to numpy ndarray.

Python Pillow Read Image to NumPy Array: A Step Guide

Preliminary

We will prepare an image which contains alpha chanel. We will start to read it using python opencv.

Python OpenCV Read an Image to NumPy NdArray A Beginner Guide - OpenCV Tutorial

This image is (width, height)=(180, 220), the backgroud of it is transparent.

Read image using python opencv

Import library

import cv2
import numpy as np

Read image

We can use cv2.imread() to read an image. This function is defined as:

cv2.imread(path ,flag)

path: the path of image

flag: determines the mode of reading an image

These are some values are often used in flag:

flag Description
cv2.IMREAD_COLOR Load the image in BGR color format, ignore alpha channel
cv2.IMREAD_UNCHANGED Similar to cv2.IMREAD_COLOR. Including alpha channel if exist
cv2.IMREAD_GRAYSCALE Loads image in grayscale mode

We will use an example to show you how to do.

flag = [cv2.IMREAD_COLOR, cv2.IMREAD_UNCHANGED, cv2.IMREAD_GRAYSCALE] 
for f in flag:
    img = cv2.imread('opencv.png', f)
    print(type(img))
    print(img.shape)
    print(img)
    cv2.imshow('image window',img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

Run this code, we can find:

img is <class ‘numpy.ndarray’>

flag shape Data Image
cv2.IMREAD_COLOR (222, 180, 3) [[[0 0 0]
[0 0 0]
[0 0 0]

[0 0 0]
[0 0 0]
[0 0 0]]]
python opencv read image with cv2.IMREAD_COLOR
cv2.IMREAD_UNCHANGED (222, 180, 4) [[[0 0 0 0]
[0 0 0 0]
[0 0 0 0]

[0 0 0 0]
[0 0 0 0]
[0 0 0 0]]]
python opencv read image with cv2.IMREAD_UNCHANGED
cv2.IMREAD_GRAYSCALE (222, 180) [[0 0 0 … 0 0 0]
[0 0 0 … 0 0 0]
[0 0 0 … 0 0 0]

[0 0 0 … 0 0 0]
[0 0 0 … 0 0 0]
[0 0 0 … 0 0 0]]]
python opencv read image with cv2.IMREAD_GRAYSCALE

Notice:

If you read an image which does not contains alpha channel (it is not transparent) using cv2.IMREAD_UNCHANGED, you may get an shape(heigh, width, 3)

For example:

As to this image, it is not transparent.

python opencv read image which is not transparent using cv2.IMREAD_UNCHANGED

We will read it using cv2.IMREAD_UNCHANGED. You will get:

<class 'numpy.ndarray'>
(367, 384, 3)
[[[255 255 255]
  [255 255 255]
  [255 255 255]
  ...
  [255 255 255]
  [255 255 255]
  [255 255 255]]]

The effect of cv2.IMREAD_UNCHANGED is same to cv2.IMREAD_COLOR.

Leave a Reply