Python处理二进制流(二)

将生成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)




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值