janasumit2911 commited on
Commit
e4d4995
·
verified ·
1 Parent(s): 54ab784

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from PIL import Image
3
+ from ultralytics import YOLO
4
+ import requests
5
+ import json
6
+
7
+ model = YOLO("Single_Object_BB_Detection_v1.pt")
8
+
9
+ def detect_objects(images):
10
+ results = model(images, max_det=1)
11
+ all_bboxes = []
12
+ all_bboxes2 = []
13
+ for result in results:
14
+ boxes = result.boxes.xywhn.tolist()
15
+ boxes2 = result.boxes.xywh.tolist()
16
+ all_bboxes.append(boxes)
17
+ all_bboxes2.append(boxes2)
18
+ return all_bboxes, all_bboxes2
19
+
20
+ def create_solutions(image_urls, all_bboxes, all_bboxes2):
21
+ solutions = []
22
+ img_id = 1
23
+ box_id = 1
24
+ category_id = 1
25
+ for image_url, bboxes, bboxes2 in zip(image_urls, all_bboxes, all_bboxes2):
26
+ for box, box2 in zip(bboxes, bboxes2):
27
+ if isinstance(box2[0], list):
28
+ w = box2[0][2]
29
+ h = box2[0][3]
30
+ else:
31
+ w = box2[2]
32
+ h = box2[3]
33
+
34
+ area = w * h
35
+ seg = [[]]
36
+
37
+ ans = {"segmentation": seg,"area": area,"iscrowd": 0,"image_id": img_id,"bbox": box,"category_id": category_id,"id": box_id}
38
+ obj = {"url": image_url, "answer": [ans]}
39
+ solutions.append(obj)
40
+ box_id += 1
41
+ img_id += 1
42
+ return solutions
43
+
44
+ def process_images(params):
45
+ # Parse the JSON string into a dictionary
46
+ params = json.loads(params)
47
+
48
+ image_urls = params.get("image_urls", [])
49
+ api = params.get("api", "")
50
+ job_id = params.get("job_id", "")
51
+
52
+ images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls] # images from URLs
53
+
54
+ all_bboxes, all_bboxes2 = detect_objects(images) # Perform object detection
55
+ solutions = create_solutions(image_urls, all_bboxes, all_bboxes2) # Create solutions with image URLs and bounding boxes
56
+
57
+ result_url = f"{api}/{job_id}"
58
+ # send_results_to_api(solutions, result_url)
59
+
60
+ return json.dumps({"solutions": solutions}, indent=4)
61
+
62
+
63
+ inputt = gr.Textbox(label="Parameters (JSON format)")
64
+ outputs = gr.JSON()
65
+
66
+ application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="Image Detection with API Integration")
67
+ application.launch()