Python OpenCV – imdecode() Function
Last Updated :
03 Jan, 2023
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 numpy as np
import urllib.request
import cv2
with urllib.request.urlopen(url) as resp:
image = np.asarray(bytearray(resp.read()), dtype = "uint8" )
image = cv2.imdecode(image, cv2.IMREAD_COLOR)
cv2.imwrite( "result.jpg" , image)
|
Output:
Example 2: If grayscale is required, then 0 can be used as flag.
Python3
import numpy as np
import urllib.request
import cv2
with urllib.request.urlopen(url) as resp:
image = np.asarray(bytearray(resp.read()), dtype = "uint8" )
image = cv2.imdecode(image, 0 )
cv2.imwrite( "result.jpg" , image)
|
Output:
Example 3: Reading image from a file
Input Image:
Python3
import numpy as np
import urllib.request
import cv2
with open ( "image.jpg" , "rb" ) as image:
f = image.read()
image = np.asarray(bytearray(f))
image = cv2.imdecode(image, 0 )
cv2.imshow( "output" , image)
|
Output:
Share your thoughts in the comments
Please Login to comment...