client.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ''' Example client sending POST request to server (localhost:8000/detect/)and printing the YOLO results
  2. The send_request() function has a couple options demonstrating all the ways you can interact
  3. with the /detect endpoint
  4. '''
  5. import requests as r
  6. import json
  7. from pprint import pprint
  8. import base64
  9. from io import BytesIO
  10. from PIL import Image
  11. def send_request(file_list = ['./images/zidane.jpg'],
  12. model_name = 'yolov5s',
  13. img_size = 640,
  14. download_image = False):
  15. #upload multiple files as list of tuples
  16. files = [('file_list', open(file,"rb")) for file in file_list]
  17. #pass the other form data here
  18. other_form_data = {'model_name': model_name,
  19. 'img_size': img_size,
  20. 'download_image': download_image}
  21. res = r.post("http://localhost:8000/detect/",
  22. data = other_form_data,
  23. files = files)
  24. if download_image:
  25. json_data = res.json()
  26. for img_data in json_data:
  27. for bbox_data in img_data:
  28. #parse json to detect if the dict contains image data (base64) or bbox data
  29. if 'image_base64' in bbox_data.keys():
  30. #decode and show base64 encoded image
  31. img = Image.open(BytesIO(base64.b64decode(str(bbox_data['image_base64']))))
  32. img.show()
  33. else:
  34. #otherwise print json bbox data
  35. pprint(bbox_data)
  36. else:
  37. #if no images were downloaded, just display json response
  38. pprint(json.loads(res.text))
  39. if __name__ == '__main__':
  40. #example uploading image batch
  41. #send_request(file_list=['./images/bus.jpg','./images/zidane.jpg'])
  42. #example uploading image and receiving bbox json + image with bboxes drawn
  43. send_request(file_list=['./images/bus.jpg'], download_image = True)