Python OpenCV – imdecode() Function
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 modulesimport numpy as npimport urllib.requestimport 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 modulesimport numpy as npimport urllib.requestimport 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 modulesimport numpy as npimport urllib.requestimport cv2 # read th imagewith 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:



