Python OpenCV – imdecode()函数
Python cv2.imdecode()函数用于从内存缓存中读取图像数据并将其转换为图像格式。这通常用于从 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
注意:如果给定的 buf 不是图像数据,则返回 NULL。
示例 1:
Python3
#import modules
import numpy as np
import urllib.request
import cv2
# read the image url
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
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)
Python3
# import necessary modules
import numpy as np
import urllib.request
import cv2
# read image url
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
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)
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)
输出:
例 2:如果需要灰度,则可以使用 0 作为标志。
Python3
# import necessary modules
import numpy as np
import urllib.request
import cv2
# read image url
url = 'https://media.geeksforgeeks.org/wp-content/uploads/20211003151646/geeks14.png'
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)
输出:
示例 3:从文件中读取图像
输入图像:
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)
输出: