从JPEG编码的cv2.imencode字节数组中获取一个numpy数组

扎比尔·纳粹

我正在从grpc客户端以字节为单位发送图像。

在客户中

import cv2

img = cv2.imread('a.jpg')
img_encoded = cv2.imencode('.jpg', img)[1] # memory buffer, type returns <class 'numpy.ndarray'>

# encode as bytes object, so I can send
img_bytes = bytearray(img_encoded) # type bytes

如何在服务器端反转该过程以将图像作为numpy数组获取?

我可以使用imdecode,但是如何反转bytearray函数?img_bytes.decode()失败,出现UnicodeDecodeError。

破解

这里是:

import cv2
import numpy as np

img = cv2.imread('a.jpg')
img_encoded = cv2.imencode('.jpg', img)[1].tobytes()  # bytes class

# 'repair' image from byte array
nparr = np.frombuffer(img_encoded, np.byte)
img2 = cv2.imdecode(nparr, cv2.IMREAD_ANYCOLOR)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章