Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 231
Arnold Klein Avatar asked Oct 20 '18 17:10

Arnold Klein


People also ask

How do I load an image into a NumPy array?

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.

Can NumPy array store images?

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.

Can you append to a NumPy array in Python?

append() is used to append values to the end of an array.


1 Answers

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.

like image 171
JohanL Avatar answered Nov 15 '22 01:11

JohanL