cv2.imdecode(…)/cv2.imencode(…)传入参数为包含图像文件内容的内存buffer,为整个文件的内容,包含格式说明、图像数据等等,并非只有图像像素数据。
语法如下:
<1> imdecode(buf, flags)
buf: 包含图像文件的buffer
flags: 以何种形式解析图像,与cv2.imread(filename[, flags])中参数一致
返回值: 数据类型为numpy.ndarray的图像,与cv2.imread(filename[, flags])中参数一致
<2> imencode(ext, img[, params])
ext: 图像后缀,".bmp"、".jpg"等cv2模块支持的图像格式
img: 数据类型为numpy.ndarray的图像,shape为height
×
\times
× width
×
\times
×channel
params: 图像保存时的参数,与cv2.imwrite(filename, img[, params])中参数一致
返回值: 保存成功时返回长度为2的tuple,第一个元素与cv2.imwrite(…)函数返回值相同,第二个元素为数据类型为numpy.ndarray类型的图像文件内容
【sample】
In [1]: import cv2
In [2]: import numpy as np
# cv2.imdecode(...)
In [3]: img = cv2.imdecode(np.fromfile("C:\\img.bmp", np.uint8), 1)
In [4]: type(img), img.shape
Out[4]: (numpy.ndarray, (331, 500, 3))
# cv2.imencode(...)
In [5]: res = cv2.imencode(".jpg", img)
In [6]: type(res), len(res) In [7]: res[0], type(res[1])
Out[6]: (tuple, 2) Out[7]: (True, numpy.ndarray)
In [8]: res[1].shape
Out[8]: (53585, 1) # 331*500*3 = 496500
# res[1]表示将图像保存为".jpg"文件时,"
# .jpg"文件应该对应的所有内容,数据为np.uint8
# 将res[1]保存到硬盘
res[1].tofile("C:\\out.jpg")
numpy.ndarray的读取保存可以参照
【读取文件】【1】python使用numpy模块读取文件内容为二进制numpy.ndarray
【读取文件】【2】python使用numpy模块将二进制numpy.ndarray保存为文件