将图像“拆分”为字节包

2024-09-30 16:38:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为大学做一个项目,其中包括使用两个Arduino Due板和Python发送图像。我有两个代码:一个用于客户端(发送图像的人)和一个用于服务器(接收图像的人)。我知道如何发送字节并检查它们是否正确,但是,我需要将映像“拆分”为包含以下内容的包:

  • 大小为8字节且必须按以下顺序排列的标头:

    1. 第一个字节必须表示有效负载大小
    2. 接下来的三个字节必须说明总共将发送多少个包
    3. 接下来的三个字节必须说明我当前所在的包
    4. 最后一个字节必须包含错误消息的代码
  • 包含最大大小为128字节的数据的有效负载;

  • 包结束(EOP)序列(在本例中为3字节)。你知道吗

我成功地创建了包尾序列,并将其正确地附加到有效负载中以便发送,但是在创建头时遇到了一些问题。你知道吗

我正在尝试进行以下循环:

with open(root.filename, 'rb') as f:
    picture = f.read()

picture_size = len(picture)

packages = ceil(picture_size/128)
last_pack_size = (picture_size)

EOPs = 0
EOP_bytes = [b'\x15', b'\xff', b'\xd9']

for p in range(1,packages):
    read_bytes = [None, int.to_bytes(picture[(p-1)*128], 1, 'big'), 
        int.to_bytes(picture[(p-1)*128 + 1], 1, 'big')]
    if p != packages:
        endrange = p*128+1
    else:
        endrange = picture_size
    for i in range((p-1)*128 + 2, endrange):
        read_bytes.append(int.to_bytes(picture[i], 1, 'big'))
        read_bytes.pop(0)
        if read_bytes == EOP_bytes:
            EOPs += 1
    print("read_bytes:", read_bytes)
    print("EOP_bytes:", EOP_bytes)
    print("EOPs", EOPs)

我希望在最后,服务器会收到与客户端发送的相同数量的包,最后,我需要加入这些包来重新创建映像。我可以做到这一点,我只是需要一些帮助创建标题。你知道吗


Tags: to代码图像readsize字节bytespackages
1条回答
网友
1楼 · 发布于 2024-09-30 16:38:49

这里是一个如何构建你的头的演示,这不是一个完整的解决方案,但如果你只要求帮助构建头它可能是你正在寻找的。你知道吗

headerArray = bytearray()

def Main():
    global headerArray

    # Sample Data
    payloadSize = 254 # 0 - 254
    totalPackages = 1
    currentPackage = 1
    errorCode = 101   # 0 - 254

    AddToByteArray(payloadSize,1)    # the first byte must say the payload size;
    AddToByteArray(totalPackages,3)  # the next three bytes must say how many packages will be sent in total;
    AddToByteArray(currentPackage,3) # the next three bytes must say which package I'm currently at;
    AddToByteArray(errorCode,1)      # the last byte must contain a code to an error message;

def AddToByteArray(value,numberOfBytes):
    global headerArray

    allocate = value.to_bytes(numberOfBytes, 'little')
    headerArray += allocate

Main()

# Output

print(f"Byte Array: {headerArray}")

for i in range(0,len(headerArray)):
    print(f"Byte Position: {i} Value:{headerArray[i]}")

显然,我没有包含获取当前包或总包的逻辑。你知道吗

相关问题 更多 >