How to use OpenCV Library to Convert images to NumPy array In NumPy

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.

Python3




import cv2
 
image = cv2.imread('Sample.png')
 
# BGR -> RGB
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
 
cv2.imwrite('opncv_sample.png', img)
print (type(img))


Output :

<class 'numpy.ndarray'>

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 of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.  In this article we will see How to Convert images to NumPy array?

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

Similar Reads

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

Converting an image into NumPy Array

...

Using NumPy module to Convert images to NumPy array

Python provides many modules and API’s for converting an image into a NumPy array. Let’s discuss to Convert images to NumPy array in Python....

Getting back the image from converted Numpy Array

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

Using Keras API  to Convert images to NumPy array

...

Using OpenCV Library to Convert images to NumPy array

...

Conclusion

...

Contact Us