[英]What is the best way (performance) to send an numpy array (an image actually) by requests.post to an API? (python)
I wanna know how can I send a 3-dimension numpy array by requests's post method;我想知道如何通过请求的 post 方法发送一个 3 维 numpy 数组; how can compress this data, if is possible.
如果可能的话,如何压缩这些数据。 The best way could be:
最好的方法可能是:
I've see this modes:我见过这种模式:
Send as a file:作为文件发送:
requests.post(api_url, files={'image': open(img_path, 'rb')})
Send as encoded array:作为编码数组发送:
# image_np is a numpy array
_, img_encoded = cv2.imencode('.jpg', image_np)
requests.post(api_url, data=img_encoded.tobytes())
Send as a buffer:作为缓冲区发送:
buf = io.BytesIO()
plt.imsave(buf, image_np, format='jpg')
image_data = buf.getvalue()
requests.post(api_url, data=image_data)
Send as string base64:作为字符串 base64 发送:
with open(img_path, 'rb') as fp:
img_encoded = str(b64encode(fp.read()))
r = requests.post(api_url, json={'image': img_encoded})
Firstly there is not going to be perfect way which minimizes all three of the following factors:首先,不会有完美的方法来最小化以下所有三个因素:
There would be some tradeoffs, I can explain the tradeoff with each of the approaches to give you a clear understanding of each method but it is heavily dependent upon the use-case to find the perfect sweet spot among the tradeoffs made.会有一些权衡,我可以解释每种方法的权衡,以便让您清楚地了解每种方法,但是在所做的权衡中找到完美的最佳点在很大程度上取决于用例。
I will discard the less libraries part here, as you are already compressing the image in JPG format which implicitly means that you are using libJPEG internally.我将在这里丢弃较少的库部分,因为您已经以 JPG 格式压缩图像,这隐含地意味着您在内部使用 libJPEG。 And JPG does offers a pretty decent compression rate so we will go with the JPEG format only.
并且 JPG 确实提供了相当不错的压缩率,因此我们将仅使用 JPEG 格式的 go。
To decrease the payload we can try following things:要减少有效负载,我们可以尝试以下操作:
int(color/5)*5
to downsample the image color domain.int(color/5)*5
对图像颜色域进行下采样。 Minimal effect on computing time
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.