我看到你已经解决了,但同时我做了一些例子。
您可以使用tobytes() 将numpy.arraay 转换为您可以通过套接字发送的bytes。
byte_data = arr.tobytes()
您还可以使用struct 将值的长度转换为4 bytes 或height,width,depth 到12 bytes
size = len(byte_data)
byte_size = struct.pack('I', size)
width, height, depth = arr.shape
byte_width_height = struct.pack('III', width, height, depth)
然后你可以发送大小或width, height, depth
all_bytes = byte_size + byte_data
send(all_bytes)
all_bytes = byte_height_width + byte_data
send(all_bytes)
在客户端你可以先得到4 bytes的大小
byte_size = recv(4)
size = struct.unpack('I', byte_size)
或12 byes,如果你用height,width,depth发送它
byte_height_width_depth = recv(12)
height, width, depth = struct.unpack('III', byte_height_width_depth)
然后你知道字节有多少帧
byte_data = recv(size)
arr = np.frombuffer(byte_data, dtype=np.uint8)
height,width,depth 你可能也知道如何重塑它
byte_data = recv(height*width*depth)
arr = np.frombuffer(byte_data, dtype=np.uint8)
arr = arr.reshape((height, width, depth))
如果您始终使用相同的height, width, depth 框架,那么您可以只发送没有height, width, depth 的数据,甚至可以不发送`size 并在代码中使用硬编码值。
但是,如果您打算将其压缩为可能具有不同字节数的 JPG 或 PNG 发送,那么您需要将大小作为第一个值发送。
使用pickle 可以获得更多字节,因为它发送有关numpy.array 类的信息来重建它。
使用tobytes 你必须自己重建数组。
示例代码 - 模拟为send、recv。
import numpy as np
import struct
import pickle
"""Simulater socket."""
internet = bytes()
pointer = 0
def send(data):
"""Simulater socket send."""
global internet
internet += data
def recv(size):
"""Simulater socket recv."""
global pointer
data = internet[pointer:pointer+size]
pointer += size
return data
def send_frame(arr):
#height, width, depth = arr.shape
#byte_height_width_depht = struct.pack('III', width, height, depth)
byte_height_width_depht = struct.pack('III', *arr.shape)
#send(byte_height_width_depht)
byte_data = arr.tobytes()
#send(byte_data)
all_bytes = byte_height_width_depht + byte_data
send(all_bytes)
print('all_bytes size:', len(all_bytes))
print('all_bytes data:', all_bytes)
def recv_frame():
byte_height_width_depht = recv(12)
height, width, depth = struct.unpack('III', byte_height_width_depht)
byte_data = recv(height*width*depth)
arr = np.frombuffer(byte_data, dtype=np.uint8).reshape((height, width, depth))
return arr
# --- main ---
arr = np.array([
[[255, 255, 255], [255, 255, 255]],
[[255, 0, 0], [ 0, 0, 255]],
[[255, 0, 0], [ 0, 0, 255]],
[[255, 255, 255], [255, 255, 255]],
], dtype=np.uint8)
print('--- pickle ---')
data = pickle.dumps(arr)
print('pickle size:', len(data))
print('pickle data:')
print(data)
print()
arr = pickle.loads(data)
print('array:')
print(arr)
print()
print('--- send frame ---')
send_frame(arr)
print()
print('--- recv frame ---')
arr = recv_frame()
print(arr)
print()