使用Python解码来自Protobuf的图像

时间:2017-05-19 03:08:36

标签: python image opencv serialization protocol-buffers

我有一个我编码的图像,并使用protobuf发送出来,如下:

<__NSMallocBlock__: 0x600000a5f7a0>

当我收到并解析该消息时,我使用了这个:

message.image = numpy.ndarray.tobytes(image)

这给了我一个一维数组。我无法将其恢复为图像格式。我尝试过使用numpy的reshape命令,但没有运气:

image_array = numpy.frombuffer(request.image, numpy.uint8)

发送的图像为400x600像素,是3通道彩色图像。关于我缺少什么的任何建议?

1 个答案:

答案 0 :(得分:0)

您还需要存储要编码的原始图像的img.shape数据以及需要img.shape值的整个解码,以将矩阵重新整形为原始形式:

import numpy as np

# Create a dummy matrix
img = np.ones((50, 50, 3), dtype=np.uint8) * 255
# Save the shape of original matrix.
img_shape = img.shape

message_image = np.ndarray.tobytes(img)

re_img = np.frombuffer(message_image, dtype=np.uint8)

# Convert back the data to original image shape.
re_img = np.reshape(re_img, img_shape)
相关问题