# 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.

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

## Import library

import cv2
import numpy as np

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:

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:
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]]] 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]]] 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]]]

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.

<class 'numpy.ndarray'>
[255 255 255]]]