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. 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.
How should I convert my image to be able to send through requests?
Using OpenCV Library imread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.
fromarray() Function to Save a NumPy Array as an Image. The fromarray() function is used to create an image memory from an object which exports the array. We can then save this image memory to our desired location by providing the required path and the file name.
append() is used to append values to the end of an array.
It is stated at the provided link "The supported input image formats includes JPEG, PNG, GIF(the first frame)s, BMP." Thus your data must be in one of those formats. A numpy array is not suitable. It needs to be converted to e.g. a PNG image.
This is most easily done using the matplotlib.pyplot.imsave()
function. However, the result should be saved to a memory buffer (to be sent to the API), rather than to a file. The way to handle that in Python, is using an io.BytesIO()
object.
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.
Note also that the line image_data = buf.getvalue()
is not necessary. Instead the buffer contents can be used directly in the API call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With