使用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()