Search code examples
python-3.xfile-uploadpython-requestshttp-postflask-restful

Python requests - post method - send image from CV2 - ndarray not working


I have below Flask API server side code:

    def post(self):
        data = parser.parse_args()
        if not data['file']:
            abort(404, message="No images found")
        imagestr = data['file'].read()
        if imagestr:
            #convert string data to numpy array
            npimg = np.frombuffer(imagestr, np.uint8)
            # convert numpy array to image
            img = cv2.imdecode(npimg, cv2.IMREAD_UNCHANGED)

Client side code:

def detect(image):
    endpoint = "http://127.0.0.1/getimage"
    # imstring = base64.b64encode(cv2.imencode('.jpg', image)[1]).decode()
    # img_str = cv2.imencode('.jpg', image)
    # im = img_str.tostring()
    # jpg_as_text = base64.b64encode(buffer)
    # print(jpg_as_text)
    data = cv2.imencode('.jpg', image)[1].tobytes()
    files = {'file':data}
    headers={"content-type":"image/jpg"}
    response = requests.post(endpoint, files=files, headers=headers)
    return response

For the API, I am able to successfully send image through CURL and get the response.

curl -X POST -F file=@input.jpg http://127.0.0.1/getimage

However, while I tried with client code, I am unable to send the images. I am seeing that no file is received at the server side:

{'file': None}
192.168.101.57 - - [17/Aug/2020 14:56:39] "POST /getimage HTTP/1.1" 404 -

I am not sure what I am missing. Can someone please help on this?


Solution

  • According to request docs you should use the following approach to post files:

    files = {'file': ('image.jpg', open('image.jpg', 'rb'), 'image/jpg', {'Expires': '0'})}
    response = requests.post(endpoint, files=files)