使用 Python 从 Protobuf 解码图像
Decoding Image from Protobuf using Python
我有一张图像,我已经编码并使用 protobuf 发送出去,如下所示:
message.image = numpy.ndarray.tobytes(image)
当我收到并解析该消息时,我使用了这个:
image_array = numpy.frombuffer(request.image, numpy.uint8)
这给了我一个一维数组。我无法将其恢复为图像格式。我试过像这样使用 numpy 的重塑命令但没有运气:
image = image_array.reshape( 400, 600, 3 )
发送的图像为 400x600 像素,是一张 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)
我有一张图像,我已经编码并使用 protobuf 发送出去,如下所示:
message.image = numpy.ndarray.tobytes(image)
当我收到并解析该消息时,我使用了这个:
image_array = numpy.frombuffer(request.image, numpy.uint8)
这给了我一个一维数组。我无法将其恢复为图像格式。我试过像这样使用 numpy 的重塑命令但没有运气:
image = image_array.reshape( 400, 600, 3 )
发送的图像为 400x600 像素,是一张 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)