Python cv2.imdecode() 函数用于从内存缓存中读取图像数据并将其转换为图像格式。这通常用于从 Internet 有效地加载图像。
用法:cv2.imdecode(buf,flags)
参数:
- buf - 它是以字节为单位接收到的图像数据
- flags - 它指定读取图像的方式。默认值为 cv2.IMREAD_COLOR
返回:图像阵列
注意:如果给定的 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)
输出:
范例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)
输出:
相关用法
- Python OpenCV setWindowTitle()用法及代码示例
- Python OpenCV resizeWindow()用法及代码示例
- Python OpenCV waitKey()用法及代码示例
- Python OpenCV waitKeyEx()用法及代码示例
- Python OpenCV getRotationMatrix2D()用法及代码示例
- Python OpenCV destroyAllWindows()用法及代码示例
- Python OpenCV namedWindow()用法及代码示例
- Python OpenCV selectroi()用法及代码示例
- Python OpenCV getTrackbarPos()用法及代码示例
- Python OpenCV Filter2D()用法及代码示例
- Python OpenCV Canny()用法及代码示例
- Python OpenCV setTrackbarPos()用法及代码示例
- Python OpenCV getgaussiankernel()用法及代码示例
- Python OpenCV haveImageReader()用法及代码示例
注:本文由纯净天空筛选整理自bhavyajain4641大神的英文原创作品 Python OpenCV – imdecode() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。