Open In App

Python OpenCV – imencode() Function

Improve
Improve
Like Article
Like
Save
Share
Report

Python OpenCV imencode() function converts (encodes) image formats into streaming data and stores it in-memory cache. It is mostly used to compress image data formats in order to make network transfer easier.

Basic example of imencode() Function

Example 1:

We began by importing the necessary libraries, which are OpenCV and NumPy. After importing libraries, we use the imread() function to load the image, using the image path as an argument. After loading the image, we begin encoding it with the imencode() method, passing the extension of the image to be encoded as well as the loaded image as parameters. 

The outcome will differ depending on the format. If you notice, we are only saving the data of the first index of the imencode() method since it produces two outputs: whether the operation was successful or not at the zero index, and the encoded image at the first index. Now we’ll convert the encoded image to a NumPy array so we can use it. Finally, we convert this NumPy array to bytes so that it can be easily transferred. 

Used image:

gfg.png

Code:

Python3




# This code demonstrates encoding of image.
import numpy as np
import cv2 as cv
  
# Passing path of image as parameter
img = cv.imread('/content/gfg.png')
  
# If the extension of our image was 
# '.jpg' then we have passed it as 
# argument instead of '.png'.
img_encode = cv.imencode('.png', img)[1]
  
# Converting the image into numpy array
data_encode = np.array(img_encode)
  
# Converting the array to bytes.
byte_encode = data_encode.tobytes()
  
print(byte_encode)


Output: (Because the output was lengthy, only a portion of it is displayed here)

b’\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x01,\x00\x00\x00\xa0\x08\x02\x00\x00\x009\x1a\xc65\x00\ …………

Example 2: 

Used image:

openCV.png

Code:

Python3




import numpy as np
import cv2 as cv
  
img = cv.imread('/content/OpenCV.png')
img_encode = cv.imencode('.jpg', img)[1]
  
data_encode = np.array(img_encode)
byte_encode = data_encode.tobytes()
  
print(byte_encode)


Output:

b’\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x02\……..



Last Updated : 03 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads