CoolFace
Apppublic

D3V1L1810/Multiple_Bounding_Box

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py92 linesDownload Raw Back to root
1import gradio as gr2from PIL import Image3from ultralytics import YOLO4import requests5import json6import logging7 8logging.basicConfig(level=logging.INFO)9 10model = YOLO("Multiple_Object_BB_Detection_v1.pt")11 12def detect_objects(images):13    results = model(images)14    all_bboxes = []15    all_bboxes2 = []16    for result in results:17        boxes = result.boxes.xywhn.tolist()18        boxes2 = result.boxes.xywh.tolist()19        all_bboxes.append(boxes)20        all_bboxes2.append(boxes2)21    return all_bboxes, all_bboxes222 23def create_solutions(image_urls, all_bboxes, all_bboxes2):24    solutions = []  25    img_id =126    box_id =127    cat_id =128    for image_url, bbox, bbox2, file_id in zip(image_urls, all_bboxes, all_bboxes2, file_ids):       # Loop through each image ID and its corresponding prediction29 30        for subbox, subbox2 in zip(bbox, bbox2):31 32            w = subbox2[2]33            h = subbox2[3]34            area = w*h35            seg=[[]]36            ans = {"segmentation":seg, "area":area, 'iscrowd':0, "image_id":img_id, "bbox": subbox, "category_id":cat_id, "id":box_id }37            ansx=[]38            ansx.append(ans)39                            40            box_id +=141            42        solutions.append({"url": image_url,'answer':ansx, "qcUser" : None, "normalfileID": file_id })43        img_id +=144    return solutions45 46# def send_results_to_api(data, result_url):47#     # Example function to send results to an API48#     headers = {"Content-Type": "application/json"}49#     response = requests.post(result_url, json=data, headers=headers)50#     if response.status_code == 200:51#         return response.json()  # Return any response from the API if needed52#     else:53#         return {"error": f"Failed to send results to API: {response.status_code}"}54 55def process_images(params):56    try:57        params = json.loads(params)58    except json.JSONDecodeError as e:59        logging.error(f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}")60        return {"error":f"Invalid JSON input: {e.msg} at line {e.lineno} column {e.colno}"}61    62    image_urls = params.get("urls", [])63    if not params.get("normalfileID",[]):64        file_ids = [None]*len(image_urls)65    else:66        file_ids = params.get("normalfileID",[])67    # api = params.get("api", "")68    # job_id = params.get("job_id", "")69    70    if not image_urls:71        logging.error("Missing required parameters: 'urls'")72        return {"error": "Missing required parameters: 'urls'"}73    try:74        images = [Image.open(requests.get(url, stream=True).raw) for url in image_urls]  # images from URLs75    except Exception as e:76        logging.error(f"Error loading images: {e}")77        return {"error": f"Error loading images: {str(e)}"}78        79    all_bboxes, all_bboxes2 = detect_objects(images)  # Perform object detection80    solutions = create_solutions(image_urls, all_bboxes, all_bboxes2, file_ids)  # Create solutions with image URLs and bounding boxes81 82    # result_url = f"{api}/{job_id}"83    # send_results_to_api(solutions, result_url)84 85    return json.dumps({"solutions": solutions})86 87 88inputt = gr.Textbox(label="Parameters (JSON format)")89outputs = gr.JSON()90 91application = gr.Interface(fn=process_images, inputs=inputt, outputs=outputs, title="Multiple Object Detection with API Integration")92application.launch()