Cv2 convert image to array

Cv2 convert image to array DEFAULT

How to Convert images to NumPy array?

Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format ofHeight, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format. 

Modules Needed:

  • NumPy:By default in higher versions of Python like 3.x onwards, NumPy is available and if not  available(in lower versions), one can install by using
pip install numpy
  • Pillow: This has to be explicitly installed in later versions too. It is a preferred image manipulation tool. In Python 3, Pillow python library which is nothing but the upgradation of PIL only. It can be installed using
pip install Pillow

One can easily check the version of installed Pillow by using the below code

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Installed Pillow Version: 7.2.0

Loading the images via Pillow Library

Let us check for an image that is in the PNG or JPEG format. The image can be referred via its path. Image class is the heart of PIL. It has open() function which opens up an image and digital file format can be retrieved as well as pixel format.

Image Used:





Output :

PNG (400, 200) RGB

Converting an image into NumPy Array

Python provides many modules and API’s for converting an image into a NumPy array. Let’s discuss a few of them in detail.

Using NumPy module

Numpy module in itself provides various methods to do the same. These methods are – 

Method 1: Using asarray() function

asarray() function is used to convert PIL images into NumPy arrays. This function convertsthe input to an array







Output :

<class 'numpy.ndarray'> (200, 400, 3)

Method 2: Using numpy.array() function

By using numpy.array() function which takes an image as the argument and converts to NumPy array





Output :

(200, 400, 3)

In order to get the value of each pixel of the NumPy array image, we need to print the retrieved data that got either from asarray() function or array() function.





Output :

[[[111 60 0] [116 65 0] [122 69 0] ... [ 97 47 0] [ 99 47 0] [100 49 0]] [[111 61 0] [118 65 0] [122 69 0] ... [ 97 47 0] [ 99 48 0] [100 49 0]] [[118 65 0] [122 69 0] [126 73 3] ... [ 98 48 0] [100 49 0] [100 49 0]] ... [[ 96 44 7] [ 95 43 6] [ 93 41 4] ... [225 80 3] [228 80 0] [229 78 0]] [[ 93 40 6] [ 90 37 5] [ 85 32 0] ... [226 81 4] [231 80 1] [232 79 1]] [[ 89 36 4] [ 84 31 0] [ 79 26 0] ... [228 81 4] [232 81 4] [233 80 2]]]

Getting back the image from converted Numpy Array

Image.fromarray() function helps to get back the image from converted numpy array. We get back the pixels also same after converting back and forth. Hence, this is very much efficient








Output :

<class 'numpy.ndarray'> (200, 400, 3) <class 'PIL.Image.Image'> RGB (400, 200)

Converting Images using Keras API

Keras API provides the functions for loading, converting, and saving image data. Keras is possible to run on the top of the TensorFlow framework and hence that is mandatory to have. Deep learning computer vision images require Keras API. To install it type the below command in the terminal 

pip install keras

As Keras requires TensorFlow 2.2 or higher. If not there, need to install it. To install it type the below command in the terminal.

pip install tensorflow




Output :

<class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200)

Using Keras API, convert images to Numpy Array and reverting the image from Numpy Array











Output :

<class 'PIL.PngImagePlugin.PngImageFile'> PNG RGB (400, 200) Image is converted and NumPy array information : <class 'numpy.ndarray'> type: float32 shape: (200, 400, 3) converting NumPy array into image: <class 'PIL.Image.Image'>

From the above output, we can check that the source image PIL.Image.Image and destination image types are the same.

Using OpenCV Library

OpenCV version from 3.x has DNN and Caffe frameworks, and they are very helpful to solve deep learning problems. It can be installed by using

pip install opencv-contrib-python

cv2 package has the following methods

  • imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. 
  • Then we need to convert the image color from BGR to RGB. 
  • imwrite() is used to save the image in the file.





Output :

<class 'numpy.ndarray'>


Python is a very flexible tool and we have seen ways of converting images into Numpy Array and similarly back to images using different APIs. Manipulating the converted array and forming different image data and one can feed into deep learning neural networks.



Learn to:

  • Access pixel values and modify them
  • Access image properties
  • Set a Region of Interest (ROI)
  • Split and merge images

Almost all the operations in this section are mainly related to Numpy rather than OpenCV. A good knowledge of Numpy is required to write better optimized code with OpenCV.

*( Examples will be shown in a Python terminal, since most of them are just single lines of code )*

Accessing and Modifying pixel values

Let's load a color image first:

>>> import numpy as np

>>> import cv2 as cv

>>> img = cv.imread('messi5.jpg')

You can access a pixel value by its row and column coordinates. For BGR image, it returns an array of Blue, Green, Red values. For grayscale image, just corresponding intensity is returned.

>>> px = img[100,100]

>>> print( px )

[157 166 200]

>>> blue = img[100,100,0]

>>> print( blue )


You can modify the pixel values the same way.

>>> img[100,100] = [255,255,255]

>>> print( img[100,100] )

[255 255 255]


Numpy is an optimized library for fast array calculations. So simply accessing each and every pixel value and modifying it will be very slow and it is discouraged.

The above method is normally used for selecting a region of an array, say the first 5 rows and last 3 columns. For individual pixel access, the Numpy array methods, array.item() and array.itemset() are considered better. They always return a scalar, however, so if you want to access all the B,G,R values, you will need to call array.item() separately for each value.

Better pixel accessing and editing method :

>>> img.item(10,10,2)


>>> img.itemset((10,10,2),100)

>>> img.item(10,10,2)


Accessing Image Properties

Image properties include number of rows, columns, and channels; type of image data; number of pixels; etc.

The shape of an image is accessed by img.shape. It returns a tuple of the number of rows, columns, and channels (if the image is color):

>>> print( img.shape )

(342, 548, 3)

If an image is grayscale, the tuple returned contains only the number of rows and columns, so it is a good method to check whether the loaded image is grayscale or color.

Total number of pixels is accessed by :

>>> print( img.size )


Image datatype is obtained by `img.dtype`:

>>> print( img.dtype )


img.dtype is very important while debugging because a large number of errors in OpenCV-Python code are caused by invalid datatype.

Image ROI

Sometimes, you will have to play with certain regions of images. For eye detection in images, first face detection is done over the entire image. When a face is obtained, we select the face region alone and search for eyes inside it instead of searching the whole image. It improves accuracy (because eyes are always on faces :D ) and performance (because we search in a small area).

ROI is again obtained using Numpy indexing. Here I am selecting the ball and copying it to another region in the image:

>>> ball = img[280:340, 330:390]

>>> img[273:333, 100:160] = ball

Check the results below:



Splitting and Merging Image Channels

Sometimes you will need to work separately on the B,G,R channels of an image. In this case, you need to split the BGR image into single channels. In other cases, you may need to join these individual channels to create a BGR image. You can do this simply by:


>>> b = img[:,:,0]

Suppose you want to set all the red pixels to zero - you do not need to split the channels first. Numpy indexing is faster:

>>> img[:,:,2] = 0


cv.split() is a costly operation (in terms of time). So use it only if necessary. Otherwise go for Numpy indexing.

Making Borders for Images (Padding)

If you want to create a border around an image, something like a photo frame, you can use cv.copyMakeBorder(). But it has more applications for convolution operation, zero padding etc. This function takes following arguments:

  • src - input image
  • top, bottom, left, right - border width in number of pixels in corresponding directions
  • borderType - Flag defining what kind of border to be added. It can be following types:
  • value - Color of border if border type is cv.BORDER_CONSTANT

Below is a sample code demonstrating all these border types for better understanding:

import cv2 as cv

import numpy as np

from matplotlib import pyplot as plt

BLUE = [255,0,0]

img1 = cv.imread('opencv-logo.png')

replicate = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REPLICATE)

reflect = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT)

reflect101 = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_REFLECT_101)

wrap = cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_WRAP)

constant= cv.copyMakeBorder(img1,10,10,10,10,cv.BORDER_CONSTANT,value=BLUE)







See the result below. (Image is displayed with matplotlib. So RED and BLUE channels will be interchanged):



Additional Resources


  1. 2 stone diamond engagement ring
  2. Aesthetic rooms
  3. Harmony 700 reset
  4. Stars clipart border

OpenCV cv2 imread()

You can read image into a numpy array using opencv library. The array contains pixel level data. And as per the requirement, you may modify the data of the image at a pixel level by updating the array values.

To read an image in Python using OpenCV, use cv2.imread() function. imread() returns a 2D or 3D matrix based on the number of color channels present in the image. For a binary or grey scale image, 2D array is sufficient. But for a colored image, you need 3D array.

Python OpenCV - cv2.imread() - Read Image

In this tutorial, we shall learn in detail how to read an image using OpenCV, by considering some of the regular scenarios.

We will also learn the order in which imread() function decodes the color channels from an image and how imread() treats different image extensions.

Syntax of cv2.imread()

The syntax of cv2.imread() function is given below.

where /path/to/image has to be the complete absolute path to the image. The flag is optional and one of the following possible values can be passed for the flag.

  • cv2.IMREAD_COLOR reads the image with RGB colors but no transparency channel. This is the default value for the flag when no value is provided as the second argument for cv2.imread().
  • cv2.IMREAD_GRAYSCALE reads the image as grey image. If the source image is color image, grey value of each pixel is calculated by taking the average of color channels, and is read into the array.
  • cv2.IMREAD_UNCHANGED reads the image as is from the source. If the source image is an RGB, it loads the image into array with Red, Green and Blue channels. If the source image is ARGB, it loads the image with three color components along with the alpha or transparency channel.

Example 1: OpenCV cv2 Read Color Image

In this example, we will read a color image. As the default value of the argument is , we are not passing the flag explicitly.

Python Program


Run the above python program, and you shall get the following output.

returns tuple representing (height, width, number_of_channels). Height of the image is 400 pixels, width is 640 and there are three color channels in the image. For cv2.IMREAD_COLOR, transparency channel is ignored even if present.

Example 2: OpenCV cv2 – Read Image as Grey Scale

In this example, we will read image as a grey scale image. Input can be color image or grey scale image. But, if flag argument is , the image is read as grey scale image.

Python Program


Height of the image is 400 pixels, width is 640. Each element in the array represents grey scale value at the respective pixel.

Example 3: OpenCV cv2 – Read Image with Transparency Channel

In this example, we will read an image with transparency channel. If there is a transparency channel in the image, then we can pass cv2.IMREAD_UNCHANGED to read the transparency channel along with the color channels.

Python Program


We have read all the four channels of the image. Namely Red, Green, Blue and Transparency.

imread() and Color Channels

imread() decodes the image into a matrix with the color channels stored in the order of Blue, Green, Red and A (Transparency) respectively.

If (400, 640, 4) is the shape of the image, then

  • (:, :, 0) represents Blue channel
  • (:, :, 1) represents Green channel
  • (:, :, 2) represents Red channel
  • (:, :, 3) represents Transparency channel

imread() and File Extensions

There are many extensions used for images based on the operating system, compression technique, etc.

When imread() method reads image, it does not consider the extension of the image file name to determine the format of the image. But decides the extension based on the format present in the file data.

imread() supports JPEGs, PNGs, and TIFFs across all platforms. But for the combination of other formats and Operating Systems, imread() may consider the operating system level codecs. You may refer the official documentation of imread() for these special scenarios.


Concluding this tutorial of Python Examples, we learned to use cv2 imread() method to read an image into a Python Array.

Tutorial -2 Image representation, cv2.imread() and cv2.imwrite()

When the image file is read with the OpenCV function , the order of colors is BGR (blue, green, red). On the other hand, in Pillow, the order of colors is assumed to be RGB (red, green, blue).

Therefore, if you want to use both the Pillow function and the OpenCV function, you need to convert BGR and RGB.

You can use the OpenCV function or simply change the order of .

This article describes the following contents.

  • OpenCV is BGR, Pillow is RGB
  • Convert BGR and RGB with OpenCV function
  • Convert BGR and RGB without using

OpenCV is BGR, Pillow is RGB

When reading a color image file, OpenCV reads as a NumPy array of . The order of color is BGR (blue, green, red).

The OpenCV function that saves an image assumes that the order of colors is BGR, so it is saved as a correct image.


bgr opencv imwrite

When performing image processing with Pillow, you can convert to a object with , but in Pillow the color order assumes RGB (red, green, blue).

Therefore, if the of the image read by OpenCV is converted to a object and saved, the image with the wrong color is saved.

bgr pillow save

If you want to convert and objects to use both Pillow and OpenCV functions, you need to convert BGR and RGB.

Convert BGR and RGB with OpenCV function cvtColor()

Various color spaces such as RGB, BGR, HSV can be mutually converted using OpenCV function .

Refer to the following document for the value to be specified for the parameter .

When is , BGR is converted to RGB.

When converted to RGB, it will be saved as a correct image even if it is saved after being converted to a object.


rgb pillow save

When converted to RGB and saved with OpenCV , it will be an incorrect color image.

rgb opencv imwrite

The parameter when converting from RGB to BGR is . Use this when reading an image file as a , convert it to , and save it using OpenCV .


Convert BGR and RGB without using cvtColor()

Converting BGR and RGB can be realized without using .

There are several ways, for example, as follows.



To array convert image cv2

“how to convert cv2 image to numpy array” Code Answer’s

Python answers related to “how to convert cv2 image to numpy array”

Python queries related to “how to convert cv2 image to numpy array”

Browse Python Answers by Framework

More “Kinda” Related Python Answers View All Python Answers »

  • python comment header
  • how to make a comment python
  • save dataframe to csv
  • python find in list
  • linux ubuntu install python 3.7
  • how to upgrade 3.6 to 3.7 on linux
  • combining 2 dataframes pandas
  • python get square root
  • UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 6148: character maps to <undefined>
  • web scraping python
  • python csv reader
  • selenium webdriver python
  • selenium getting started
  • selenium python
  • installing django
  • python absolute value
  • python main function
  • how to define main in python
  • sort a dataframe by a column valuepython
  • sort_values
  • order pandas dataframe by column values
  • multiline comment python
  • get request python
  • python requirements.txt
  • python reverse string
  • how to make a python list
  • how to install python libraries
  • install pip on windows 10 python 3.9
  • No module named env.__main__; 'env' is a package and cannot be directly executed
  • python 2 decimal places
  • python ascii
  • plt figsize
  • increase figure size in matplotlib
  • seaborn figure size
  • python try catch
  • replacing values in pandas dataframe
  • how to round a float in python
  • round in python
  • create new django project
  • python replace regex
  • copy a list python
  • python convert json to pandas dataframe
  • python rename file
  • raise python
  • python3 iterate through indexes
  • open file python
  • python file handling
  • python open file
  • python input integer
  • python time a funciton
  • install python in mac
  • python choose random element from list
  • replace values of pandas column
  • check tensorflow version
  • how to check current version of tensorflow
  • python get filename from path
  • how to print something in python
  • numpy list to array
  • python startswith
  • python convert string to bytes
  • python version
  • scikit learn svm
  • ParserError: Error tokenizing data. C error: Expected 1 fields in line 87, saw 2
  • import matplotlib.pyplot as plt
  • how to import matplotlib in python
  • python kill script
  • stop if code python
  • python exit program
  • exit python script
  • print colored text python
  • python debugger
  • python shuffle list
  • sorting by column in pandas
  • copy files python
  • how to coppy a file in python
  • python os copy
  • python read file list from directory
  • python copy file
  • python os file copy
  • No module named 'rest_framework'
  • check if string is empty python
  • install django rest framework
  • python os remove file
  • python access index in for loop
  • python comment
  • December global holidays
  • fibonacci sequence python
  • fibonacci
  • python datetime from string
  • python string to datetime
  • import csv file in python
  • how to read csv from local files
  • python find the key with max value
  • load csv file using pandas
  • python requests header
  • how to print error in try except python
  • string palindrome in python
  • palindrome python
  • pandas read excel
  • python plot
  • is int python
  • prime number in python
  • enumerate python
  • python round up
  • python install pil
  • pil python install
  • python list files in current directory
  • count values pandas
  • value_counts pandas
  • value_counts() in pandas
  • remove substring python
  • create a dataframe python
  • convert int to binary python
  • change dataframe column type
  • django rest framework
  • django rest
  • pip install django rest framework
  • base64 encode python
  • python convery list to array
  • convert list to array python
  • ModuleNotFoundError: No module named 'tkinter'
  • how to install tkinter
  • python square root
  • how to install python3 in ubuntu
  • gridsearchcv
  • pandas read from excel
  • python get dictionary keys
  • counter method in python
  • count nan pandas
  • django create app
  • sort list of dictionaries by key python
  • sort list of dictionaries python by value
  • how to install pyaudio in python
  • how to install pyaudio
  • throwing an exception python
  • how to use timeit in python 3
  • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe7 in position 5: invalid continuation byte
  • capitalize string python
  • python check key press
  • python datetime string
  • create and use python classes
  • python for loop
  • how to print the square root of a number in python
  • one-line for loop python
  • average value of list elements in python
  • pip install specific version
  • django make migrations
  • convert to timestamp python
  • numpy merge arrays
  • print no new line python
  • python largest value in list
  • iterate through dictionary
  • list files in directory python
  • check if anything in a list is in a string python
  • dataframe to list
  • panda dataframe to list
  • how to convert dataframe to list in python
  • pandas to list
  • create dictionary comprehension python
  • python loop through dictionary
  • remove item from list python
  • django user fields
  • python check if folder exists
  • create new env in anaconda
  • how to create virtual environment in anaconda
  • new env in conda
  • How to create an env to use in vs code using anaconda
  • create an environment in conda
  • how to create miniconda environment
  • conda env
  • conda create environment
  • logistic regression algorithm in python
  • json dump to file
  • Quick Sort python
  • partition algorithm python code
  • python calculate factorial
  • set index to column pandas
  • sklearn random forest
  • python time delay
  • try catch in python
  • try catch python
  • python logging to file
  • # Python program to check if the input number is odd or even.
  • odd or even python
  • Curl in python
  • install python on ubuntu
  • python if __main__
  • write json to file python
  • how to save json file in python
  • write json pythonb
  • python removing \n from string
  • decode base64 python
  • python os if file exists
  • python directory contains file
  • convert column in pandas to datetime
  • how to run a .exe through python
  • pygame example
  • create folder python
  • create data dir in python
  • discord py get user by id
  • virtual environment python
  • pip install virtualenv windows
  • create virtual env
  • how to use virtual environment python
  • Pandas groupby aggregate multiple columns
  • dataframe groupby multiple columns
  • python speech to text
  • install requirment.txt
  • create new thread python
  • install selenium python
  • python create environment variable
  • check strings last letter python
  • urllib python
  • python how to use input
  • tkinter basic
  • split string by spaces python
  • rename column name pandas dataframe
  • how to make a discord bot python
  • python comments
  • python exception list
  • how to get a row from a dataframe in python
  • how to find python version
  • check python version
  • amazon cli on commadline
  • how to find the version of python command linw
  • python check version
  • python return column names of pandas dataframe
  • python sort list in reverse
  • how to sort list in descending order in python
  • append to front of list python
  • list comprehension python if else
  • how to label column names and row names in pandas dataframe
  • python type on keyboard
  • python how to rename columns in pandas dataframe
  • round to the nearest integer python
  • format time python
  • print key of dictionary python
  • how to convert a list into a dataframe in python
  • timestamp to date python
  • python how to read a xlsx file
  • python string interpolation
  • datetime python timezone
  • how to check datatype of column in dataframe python
  • pipenv
  • redirect django
  • python create uuid
  • how to plot a bar using matplotlib
  • play videos in python
  • python play audio snippet
  • play music from python
  • how to check if datapoint is in pandas column
  • find nan value in dataframe python
  • except as Exception:
  • numpy linspace
  • start a simple http server python3
  • python bmi calculator code
  • python auto clicker
  • pandas count rows in column
  • how to convert types of variablesin python
  • python input().strip()
  • pyqt5 change button color
  • import data in pandad
  • python fiboncci
  • choice random python
  • remove 0 values from dataframe
  • how to remove no data times plotly
  • python send image in post request with json data
  • python alphabet
  • use of kwargs and args in python classes
  • how to set up pygame
  • python eval set variable
  • dobj in spacy
  • IndentationError: unexpected indent
  • create python package
  • python create n*n matrix
  • python find second occurrence in string
  • 3d plots in python
  • ls.ProgrammingError: permission denied for table django_migrations
  • confidence intervals in python
  • python library to convert decimal into octal and hexadecimal
  • convert a data frame column values to list
  • train test split python
  • run a python script with python and catch command line output
  • flat numpy array
  • code button trong python
  • variable plus one python
  • save changes flask sqlalchemy
  • pca python
  • why when I merge my label cluster with my dataframe i get more row
  • python print function arguments
  • colab save figure
  • setting Pycharm as a pyqgis IDE
  • python raise filenotfounderror
  • zip function python 3
  • nlargest hierarchy series pandas
  • python check if all dictionary values are False
  • check python version kali linux
  • pause program python
  • python window icon on task bar
  • django show image in admin page
  • python get human readable file size
  • class Meta: unique_together = ('category_name',)
  • F-Strings decilamal places
  • python pretty print
  • how to pass primary key to url django
  • add row in db django
  • how to add input box in tkinter
  • prog = {'Python':'C++', 'Java':['JavaScript', 'JSON', 'C++']'Python Console':('Lucy', 'Dad')} SyntaxError: invalid syntax
  • make tkinter btn disable
  • DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
  • python tkinter label
  • .text python
  • numpy shape
  • change ticks font size matplotlib python
  • about strptime()
  • how to make a series in python alternating between + and -
  • python subset
  • 4 in a rpw pygame code
  • gdscript tween
  • hello kitt
  • django admin required decorator
  • dask show progress bar
  • check tf verison
  • recursively count string
  • argparse type
  • how to get each digit of a number
  • analog of join in pathlibn
  • python3 create list from string
  • what if functionality not in the requirements
  • connect elasticsearch cloud with python terminal
  • Construct a tuple
  • string float to round to 2dp python
  • python pandas cumulative return
  • how to install pandas for aws sam local
  • k and M to int in pandas
  • python typing effect
  • python substring in string
  • find common values in different dataframes pandas
  • pandas create dataframe from list of lists
  • All objects and constants needed to use the ldap3 library can be imported from the ldap3 namespace
  • set jupyer color to dark
  • changing default python version ubuntu
  • how to kill yourself
  • how to set background image in tkinter frame
  • convert list into integer python
  • check corently installed epython version
  • random name generator python
  • hue seaborn
  • To install a specific version, type the package name followed by the required version:
  • how to subtract in python
  • python unsupported operand type(s) for /: 'str' and 'str'
  • how to rescale data pandas
  • bot that only responds to certain roles
  • number length python
  • can you assign a pid to a process via python
  • pyhton permutations
  • append to a tuple
  • sklearn.utils.bunch to dataframe
  • rotate picture in opencv2 python
  • heapq python how to use comparator
  • assigning values in python
  • encoding and decoding in python
  • how to convert character to factor in python
  • python load file with multiple jsons
  • make each element in a list occur once python
  • pandas print full dataframe
  • python not null
  • show post id on django admin interface
  • pandas add character to string
  • max and min int in python
  • get guild member list
  • python tkinter programming project ideas
  • 'xml.etree.ElementTree.Element' to string python
  • random in python3
  • gtk entry focus python
  • how to convert categorical data to binary data in python
  • concat tensors pytorch
  • python flask rest api
  • comma separated variables python
  • pandas convert hex string to int
  • python panda count excel sheet
  • pyplot set x range
  • how to know the number of CPu using python
  • poetry python download windows
  • get_dummies
  • find string in string python
  • name =input ("hello how are you ") if name==("good"): print ("Thats nice") else print("stfu")
  • pygame rotate image
  • python find file in directory
  • data[:,:2]
  • python 3.3 release date
  • python big comment
  • python zip function
  • convert base64 to image python
  • python if statement multiple lines
  • how to playsound in python
  • merge sort of two list in python
  • python writelines
  • pyhton comment
  • python print version python
  • php datatables serverside
  • popup flutter
  • data parsing app python
  • ubuntu 20.10 python 3.8
  • nltk python
  • binary tree
  • import skbuild ModuleNotFoundError: No module named 'skbuild'
  • pandas convert series of datetime to date
  • explain modulo python
  • what is python
  • run file
  • how to draw image in tkinter
  • how to count all files on linux
  • python what does yield do
  • pandas dataframe get number of columns
  • calculate volume of mask
  • sum of digits python recursive
  • tensorflow for python 3.9
  • how to obtain the content of brackets
  • how to make a discord bot
  • progress apply
  • how to load pretrained model in pytorch
  • dataframe passed by reference or value
  • python loop program
  • run python without terminal
  • generate random int python
  • I've a date column messed up with different date formats how to fix it in power bi
  • how do you see if a data type is an integer python
  • python tk
  • trim strings python
  • find last appearance python
  • pandas define how you want to aggregate each column
  • cut part of video ffmpeg
  • how to move a column in pandas dataframe
  • lofi hip hop radio online
  • typing test python
  • dynamic array python numpy
  • django reverse lazy
  • floor and ceil in python
  • How do I run two python loops concurrently?
  • selenium screenshot python user agent
  • how to find ip address of website using python
  • No module named 'sklearn.utils.linear_assignment
  • shuffle columns pandas
  • what is modulus in python
  • python string to array
  • annot identify image file '/home/ellis/CB/Django-Ecommerce/media_root/default.jpg'
  • custom attribute selenium
  • como agregar elementos a un array en python
  • can you edit string.punctuation
  • python detect color on screen
  • python string variable
  • saaaaaaaaaaaaa
  • python pygame screen example

How to convert images to NumPy arrays - 20

In Python and OpenCV, you can read (load) and write (save) image files with and . Images are read as NumPy array .

This article describes the following contents.

  • Read and write images in color (BGR)
    • Read an image file with
    • Write as an image file with
  • Read and write images in grayscale
    • Read an image file with
    • Write as an image file with
  • Notes on
    • does not raise an exception
    • JPEG library
  • If images cannot be read with
    • Check the current directory
    • Supported formats for

It is also possible to read image files as using Pillow instead of OpenCV.

The following image is used as an example.


Read and write images in color (BGR)

Read an image file with cv2.imread()

Color image files are read as a 3D ndarray of .


Note that the color order is BGR instead of RGB. As an example, set 0th (B: blue) and 1st (G: green) to 0 (black).

lena red

If you want to convert BGR and RGB, please refer to the following article.

Write ndarray as an image file with cv2.imwrite()

To save as an image file, set the file path and object to .

The format of the image file is automatically determined from the file path extension. If it is , it is saved as JPEG, and if it is , it is saved as PNG.

lena red

Format-specific parameters can be specified for the third parameter. Specify with a list like .

For parameter ID (flag), refer to the official document below.

For example, the quality of JPEG is specified by . is the lowest and is the highest, the default is .

If saved as :


lena red low quality

If saved as :


lena red high quality

Note that JPEG is lossy compression, so even if it is the highest quality , when the saved image is reloaded, a difference occurs with the original pixel value. If you want to save the original image as it is, save it as PNG or BMP.

Read and write images in grayscale

Read an image file with cv2.imread()

By passing as the second argument of , a color image file can be read in grayscale (black and white). Since is equivalent to , even passing is OK.

It is useful for detecting edges and other situations where color information is not required.

In this case, the image is read as 2D of .


You can read the image file as color and convert it to grayscale with and .

Because with perform codec-dependent conversions instead of OpenCV-implemented conversions, you may get different results on different platforms. with is safer to use if you want to handle pixel values strictly.

Write ndarray as an image file with cv2.imwrite()

If 2D of is specified as the argument of , it is saved as a grayscale image file.

lena gray

If you want to save a color image (3D ) as a grayscale image file, convert it to grayscale with and .

If you save 2D to a file and read it again with , it will be read as 3D in which each color is the same value.

It does not automatically read in as a two-dimensional array.


Notes on cv2.imread()

cv2.imread() does not raise an exception

Even if a nonexistent path is specified, does not raise an exception and return . An error will occur when a user performs some operation assuming it is read as .


Even if the file exists, is returned if OpenCV does not support it.

Because is regarded as , you can check whether the image was loaded correctly as follows.



JPEG library

As you can see in the GitHub issue below, the library used to process JPEGs depends on the OpenCV version, platform, etc. Therefore, even if the same file is read, there may be differences in the values if the environment is different.

Reading of JPEG images is not bit-exact operation. It depends on used library (libjpeg/libjpeg-turbo) and/or versions, platforms (x86/ARM), compiler options. imread and imwrite cause differences in image pixels · Issue #10887 · opencv/opencv

If images cannot be read with cv2.imread()

Check the current directory

Like the built-in function , with and , you can specify the path of a file with one of the following methods:

  • Relative path from the current directory
  • Absolute path

If the file should be there but cannot be read, it is often because of a simple mistake that the current directory is different from what is expected.

You can check the current directory with .

Supported formats for

Of course, image files in formats not supported by OpenCV cannot be read.

The following formats are supported by of OpenCV . See also the notes at the link.

  • Windows bitmaps - .bmp, .dib (always supported)
  • JPEG files - .jpeg, .jpg, *.jpe (see the Note section)
  • JPEG 2000 files - *.jp2 (see the Note section)
  • Portable Network Graphics - *.png (see the Note section)
  • WebP - *.webp (see the Note section)
  • Portable image format - .pbm, .pgm, .ppm .pxm, *.pnm (always supported)
  • PFM files - *.pfm (see the Note section)
  • Sun rasters - .sr, .ras (always supported)
  • TIFF files - .tiff, .tif (see the Note section)
  • OpenEXR Image files - *.exr (see the Note section)
  • Radiance HDR - .hdr, .pic (always supported)
  • Raster and Vector geospatial data supported by GDAL (see the Note section)
    OpenCV: Image file reading and writing

See below for other versions.

You can check information about libraries and so on in the section of .

checks the format of a file by its content not by its extension. If the file cannot be read, check whether the file can be read by another application (check whether the file is not corrupted).

The function determines the type of an image by the content, not by the file extension. OpenCV: Image file reading and writing


Now discussing:


324 325 326 327 328