[英]What is the best way (performance) to send an numpy array (an image actually) by requests.post to an API? (python)
我想知道如何通過請求的 post 方法發送一個 3 維 numpy 數組; 如果可能的話,如何壓縮這些數據。 最好的方法可能是:
我見過這種模式:
作為文件發送:
requests.post(api_url, files={'image': open(img_path, 'rb')})
作為編碼數組發送:
# image_np is a numpy array
_, img_encoded = cv2.imencode('.jpg', image_np)
requests.post(api_url, data=img_encoded.tobytes())
作為緩沖區發送:
buf = io.BytesIO()
plt.imsave(buf, image_np, format='jpg')
image_data = buf.getvalue()
requests.post(api_url, data=image_data)
作為字符串 base64 發送:
with open(img_path, 'rb') as fp:
img_encoded = str(b64encode(fp.read()))
r = requests.post(api_url, json={'image': img_encoded})
首先,不會有完美的方法來最小化以下所有三個因素:
會有一些權衡,我可以解釋每種方法的權衡,以便讓您清楚地了解每種方法,但是在所做的權衡中找到完美的最佳點在很大程度上取決於用例。
我將在這里丟棄較少的庫部分,因為您已經以 JPG 格式壓縮圖像,這隱含地意味着您在內部使用 libJPEG。 並且 JPG 確實提供了相當不錯的壓縮率,因此我們將僅使用 JPEG 格式的 go。
要減少有效負載,我們可以嘗試以下操作:
int(color/5)*5
對圖像顏色域進行下采樣。 對計算時間的影響最小
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.