Python——cv2.imdecode(...)/cv2.imencode(...)从内存buffer读取/存储图像

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保存为文件

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值