grpc 图片序列化与反序列化

使用cv2读入图片保存为tobytes格式时,需要同时保存图片的shape 的信息,这样才能将bytes再次恢复成原来的图片。用二进制保存图片更简单

 


import event_pb2

# test = event_pb2.MediaTXT()
# test.text = "Hello"
# text_serialize = test.SerializeToString()
# print(text_serialize)
#
# test_msg = event_pb2.MediaTXT()
# test_msg.ParseFromString(text_serialize)
# print(test_msg)


import os
video_dir = '/home/lc/文档/from_thinkpad/windows/source_code/media'

img_path = os.path.join(video_dir, "4.jpg")
# with open(img_path,'rb') as fr:
#     content = fr.read()
#
# img_binary = event_pb2.MediaImage(data=content)
# img_serialize = img_binary.SerializeToString()
#
# img_msg = event_pb2.MediaImage()
# img_msg.ParseFromString(img_serialize)
#
# with open('./logs/test.jpg', 'wb') as fout:
#     fout.write(img_msg.data)


import cv2
import matplotlib.pyplot as plt
import numpy as np
import math

img_cv2 = cv2.imread(img_path)
shape = img_cv2.shape
plt.imshow(img_cv2)
plt.show()

img_cv2_bytes = img_cv2.tobytes()



img_pb2_bytes = event_pb2.MediaImage(data=img_cv2_bytes)
img_event = event_pb2.Event(image=img_pb2_bytes)
img_event_serialize = img_event.SerializeToString()

img_event_msg = event_pb2.Event()
img_event_msg.ParseFromString(img_event_serialize)

img_bytes = img_event_msg.image.data
ndarray = np.frombuffer(img_bytes, dtype=np.uint8)
img_from_bytes=ndarray.reshape(shape)
plt.imshow(img_from_bytes)
plt.show()







 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值