OpenCV imdecode() Function in Python (original) (raw)
Last Updated : 09 Apr, 2025
**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.
Example: Decoding and Saving an Image from URL in Color
This example demonstrates how to download an image from a URL, decode it in color, and save it locally.
Python `
import numpy as np import urllib.request import cv2
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
with urllib.request.urlopen(url) as resp:
i = np.asarray(bytearray(resp.read()), dtype="uint8")
i = cv2.imdecode(i, cv2.IMREAD_COLOR)
cv2.imwrite("result.jpg", i)
`
**Output:
**Explanation: The code fetches image data from a specified URL using **urllib.request.urlopen(), converts it to a NumPy array, and decodes it using **cv2.imdecode() with the **cv2.IMREAD_COLOR flag to maintain the color information. The decoded image is then saved as a ****.jpg** file using **cv2.imwrite().
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 Type:
- If the input byte data is a valid image, the function returns a **NumPy **ndarray, representing the image in the specified color mode.
- If buf given is not image data then **NULL will be returned.
Examples of imdecode() Function
Example 1: Decoding and Saving an Image from URL in Grayscale
If grayscale is required, then 0 can be used as flag.
Python `
import numpy as np import urllib.request import cv2
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
with urllib.request.urlopen(url) as resp:
i = np.asarray(bytearray(resp.read()), dtype="uint8")
i = cv2.imdecode(i, 0)
cv2.imwrite("result.jpg", i)
`
**Output:
**Explanation: Similar to the first example, the image is fetched and converted into a NumPy array. However, in this case, **cv2.imdecode() is used with the **0 flag, which decodes the image in grayscale. The resulting grayscale image is then saved as a ****.jpg** file using **cv2.imwrite().
Example 2: Reading image from a file
This code demonstrates how to read an image from a local file, decode it in grayscale, and display it using OpenCV.
**Input Image:
Python `
import numpy as np import urllib.request import cv2
with open("image.jpg", "rb") as i: f = i.read()
i = np.asarray(bytearray(f), dtype=np.uint8)
i = cv2.imdecode(i, 0)
cv2.imshow("output", i)
cv2.waitKey(0)
cv2.destroyAllWindows()
`
**Output:
**Explanation: The image is read from the local file **image.jpg in binary mode, then converted into a NumPy array. The **cv2.imdecode() function is used to decode the image into grayscale. The grayscale image is then displayed using **cv2.imshow(), and the window remains open until a key is pressed.