从 JPEG 编码(按 cv2.imencode)bytearray 取回一个 numpy 数组

Get back a numpy array from JPEG encoded (by cv2.imencode) bytearray

我正在以字节形式从 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)