使用Python从Protobuf解码图像

4

我有一张图片已经使用protobuf进行编码,并像下面这样发送出去:

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

当我接收并解析该消息时,我使用以下代码:
image_array = numpy.frombuffer(request.image, numpy.uint8)

这给了我一个一维数组,但我无法将其转换为图像格式。我曾尝试使用numpy的reshape命令,但未成功:
image = image_array.reshape( 400, 600, 3 )

发送的图像大小为400x600像素,是一个三通道的彩色图像。您有什么建议吗?

你尝试过使用 np.reshape 吗? - ZdaR
我已经尝试过了,但是没有成功。我已经将我使用的reshape命令添加到原始问题中。 - badrobit
1个回答

3
您还需要存储要编码的原始图像的 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)

这就是我使用image_array.reshape(400, 600, 3)所做的事情,其中400、600、3是image.shape的输出,我只是硬编码以确保它能正常工作。 - badrobit
image_array.reshape(600, 600, 3)与image_array.reshape((600, 600, 3))不同。请尝试使用前者。 - ZdaR
谢谢!这使我得到了一个宽度和高度正确的图像,但现在它显示为全灰色,但当我将数组中的数据打印到控制台时,在传输前后它们是相同的。 - badrobit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接