Open In App

Python OpenCV – imdecode() Function

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python cv2.imdecode() function is used to read image data from a memory cache and convert it into image format. This is generally used for loading the image efficiently from the internet. 

Syntax: cv2.imdecode(buf,flags)

Parameters:

  • buf – It is the image data received  in bytes
  • flags – It specifies the way in which image should be read. It’s default value is cv2.IMREAD_COLOR

Return: Image array

Note: If buf given is not image data then NULL will be returned.

Example 1:

Python3




#import modules
import numpy as np
import urllib.request
import cv2
  
# read the image url
  
  
with urllib.request.urlopen(url) as resp:
    
    # read image as an numpy array
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
      
    # use imdecode function
    image = cv2.imdecode(image, cv2.IMREAD_COLOR)
  
    # display image
    cv2.imwrite("result.jpg", image)


Output:

Example 2: If grayscale is required, then 0 can be used as flag.

Python3




# import necessary modules
import numpy as np
import urllib.request
import cv2
  
# read image url
  
with urllib.request.urlopen(url) as resp:
  
    # convert to numpy array
    image = np.asarray(bytearray(resp.read()), dtype="uint8")
      
    # 0 is used for grayscale image
    image = cv2.imdecode(image, 0)
      
    # display image
    cv2.imwrite("result.jpg", image)


Output:

Example 3: Reading image from a file

Input Image:

Python3




# import necessayr modules
import numpy as np
import urllib.request
import cv2
  
# read th image
with open("image.jpg", "rb") as image:
    
    f = image.read()
      
    # convert to numpy array
    image = np.asarray(bytearray(f))
      
    # RGB to Grayscale
    image = cv2.imdecode(image, 0)
      
    # display image
    cv2.imshow("output", image)


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads