5

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?

2

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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. 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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.