VishnuCodes commited on
Commit
16b68f4
·
verified ·
1 Parent(s): 91b7444

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +30 -0
main.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, File, UploadFile, Response
2
+ from PIL import Image
3
+ import torch
4
+ import io
5
+
6
+ app = FastAPI()
7
+
8
+ # Load the YOLOv5 model
9
+ model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt')
10
+
11
+ @app.post("/detect/")
12
+ async def detect(file: UploadFile = File(...)):
13
+ # Read image file
14
+ image_data = await file.read()
15
+ image = Image.open(io.BytesIO(image_data))
16
+
17
+ # Perform inference
18
+ results = model(image)
19
+
20
+ # Render the results on the image
21
+ results.render()
22
+
23
+ # Convert the image to bytes
24
+ img_bytes = io.BytesIO()
25
+ image_with_boxes = Image.fromarray(results.ims[0])
26
+ image_with_boxes.save(img_bytes, format='JPEG')
27
+ img_bytes.seek(0)
28
+
29
+ # Create a response with the image
30
+ return Response(content=img_bytes.getvalue(), media_type="image/jpeg")