简体   繁体   English

使用 zlib + base64 [python] 压缩 numpy 数组

[英]compressing numpy array with zlib + base64 [python]

I'm trying to send a numpy array through the python requests module to a flask server.我正在尝试通过 python requests模块将 numpy 数组发送到 flask 服务器。

First, I compressed the numpy array with zlib, then used base64 to encode the data, then tried to decode and decompress but it's not working.首先,我使用 zlib 压缩了 numpy 数组,然后使用base64对数据进行编码,然后尝试解码和解压缩,但它不起作用。

import numpy as np 
import base64
import zlib
import requests

frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
print('compressed')
print(data)
print(len(data))
print(type(data))

data = base64.b64encode(frame)
print('b64 encoded')
print(data)
print(len(data))
print(type(data))

data = base64.b64decode(data)
print('b64 decoded')
print(data)
print(len(data))
print(type(data))

data = zlib.decompress(data)
print('b64 decoded')

I'm getting the following error:我收到以下错误:

Traceback (most recent call last):
  File "client.py", line 26, in <module>
    data = zlib.decompress(data)
zlib.error: Error -3 while decompressing data: incorrect header check

data = base64.b64encode(frame) should be data = base64.b64encode(frame)应该是

b64encode (data)

You're accidentally encoding the wrong thing...你不小心编码错误的东西......

I just realized after considering the extra length for base64 encoded string, I can completely get rid of it.在考虑了 base64 编码字符串的额外长度后,我才意识到,我可以完全摆脱它。

So, the following code snippet does what I need, it compresses the numpy array, then I can get the original array back without using base64 .所以,下面的代码片段做了我需要的,它压缩了numpy数组,然后我可以在不使用base64的情况下取回原始数组。 It gets rid of some of the overhead.它消除了一些开销。

import numpy as np 
import base64
import zlib
import requests

frame = np.random.randint(0,255,(5,5,3)) # dummy rgb image
# compress
data = zlib.compress(frame)
print('compressed')
print(data)
print(len(data))
print(type(data))


data = zlib.decompress(data)
print('b64 decoded')


data = np.frombuffer(data, dtype=np.uint8)

print(data)
print(type(data))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM