将生成stuct字串封装为一个函数data2Struct,废话不多数,如下:
import struct
import numpy as np
import cv2
def str2St(bStr):
return str( len(bStr)) + 's'
def data2Struct(*args):
st = ''
list = []
for i in range(len(args)):
if args[i][1] != 's':
st = st + args[i][1]
else:
st = st + str2St(args[i][0])
list.append(args[i][0])
return st,list
name = 'picture.jpg'
name_bin = name.encode('utf-8') #转二进制
img = cv2.imread(name) #ndarray类型,按bgr顺序排序,uint8类型
img_bin = img.tostring() #bytes类型 或者用tobytes()
namelen_uchar = len(name_bin) # B 1字节
width_ushort = img.shape[1] # H 2字节
height_ushort = img.shape[0] # H 2字节
datalen_uint = len(img_bin) # I 4 字节
#产生64字节的字串, 字串填充文件名
data = np.zeros(shape=(64),dtype='uint8')
data[0:namelen_uchar] = np.fromstring(name, dtype='uint8')
name_bytes = data.tobytes()
st,args = data2Struct((name_bytes, 's'),(width_ushort,'H'), (height_ushort,'H'), (datalen_uint,'I'), (img_bin,'s'))
pk = struct.pack(st, *args)
#struct解包
name_bytes, width_ushort, height_ushort, databytes_uint, img_bin = struct.unpack(st, pk)
name = name_bytes.decode('utf8')
name = name[0:name.rfind('.')] + 'recv.jpg'
print(name)
#将二进制字节流转为numpy格式(ndarry)
img_recv = np.frombuffer(img_bin, dtype=np.uint8).reshape([height_ushort, width_ushort, 3])
cv2.imwrite(name, img_recv)