简体   繁体   English

发送图像(作为 numpy 数组)'requests.post'

[英]send an image (as numpy array) 'requests.post'

I am bit puzzled with a very simple thing: I am using an online service for image processing and to send my image I'm using我对一件非常简单的事情感到困惑:我正在使用在线服务进行图像处理并发送我正在使用的图像

var_0 = requests.post(api_url, params=params, headers=headers, data=image_data)

where image_data should be encode as a binary string.其中image_data应编码为二进制字符串。 For example, the following example works properly:例如,以下示例正常工作:

image_data = open(image_path, "rb").read()
var_0 = requests.post(api_url, params=params, headers=headers, data=image_data)

However, in some cases I need to send an image while it is already opened and is in an numpy.array format.但是,在某些情况下,我需要在图像已经打开并且采用 numpy.array 格式时发送图像。

How should I convert my image to be able to send through requests?我应该如何转换我的图像以便能够通过请求发送?

It is stated at the provided link "The supported input image formats includes JPEG, PNG, GIF(the first frame)s, BMP." 在提供的链接中声明“支持的输入图像格式包括JPEG,PNG,GIF(第一帧),BMP”。 Thus your data must be in one of those formats. 因此,您的数据必须采用这些格式之一。 A numpy array is not suitable. numpy数组不适合。 It needs to be converted to eg a PNG image. 需要将其转换为例如PNG图像。

This is most easily done using the matplotlib.pyplot.imsave() function. 使用matplotlib.pyplot.imsave()函数最容易做到这一点。 However, the result should be saved to a memory buffer (to be sent to the API), rather than to a file. 但是,结果应保存到内存缓冲区(发送到API),而不是文件。 The way to handle that in Python, is using an io.BytesIO() object. 在Python中处理该问题的方法是使用io.BytesIO()对象。

Taken together, a solution to the problem is 综上所述,解决该问题的方法是

import io
import numpy as np
import matplotlib.pyplot as plt

buf = io.BytesIO()
plt.imsave(buf, image_np, format='png')
image_data = buf.getvalue()
var_0 = requests.post(api_url, params=params, headers=headers, data=image_data)

where image_np is the image as a numpy array. 其中image_np是作为numpy数组的图像。

Note also that the line image_data = buf.getvalue() is not necessary. 还要注意,行image_data = buf.getvalue()是不必要的。 Instead the buffer contents can be used directly in the API call. 相反,缓冲区内容可以直接在API调用中使用。

One way to solve this is to use the OpenCV library, maybe it is very useful for some people since when working with images it is very common to work with OpenCV.解决这个问题的一种方法是使用 OpenCV 库,也许它对某些人非常有用,因为在处理图像时,使用 OpenCV 是很常见的。 Here is my solution:这是我的解决方案:

import cv2, requests
import numpy as np
numpy_image = cv2.imread("/path/to/image.png")
api_url = "your_api_url"
_ , encoded_image = cv2.imencode('.jpg', numpy_image)
response = requests.post(api_url, data = encoded_image.tobytes()).json()

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

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