Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0125-preview· openaiHugging Face Suzhen/CodeChat

làm gradio import cv2 Specify the path to your image imagepath =…

  1. User

    làm gradio
    import cv2

    Specify the path to your image

    image_path = '/content/drive/MyDrive/yolov9/yolov9/runs/detect/exp4/1.jpg'

    Read the image to get its dimensions

    image = cv2.imread(image_path) image_height, image_width, _ = image.shape

    detections_path = '/content/drive/MyDrive/yolov9/yolov9/runs/detect/exp4/labels/1.txt'

    bboxes = [] class_ids = [] conf_scores = []

    with open(detections_path, 'r') as file: for line in file: components = line.split() class_id = int(components[0]) confidence = float(components[5]) cx, cy, w, h = [float(x) for x in components[1:5]]

        # Convert from normalized [0, 1] to image scale
        cx *= image_width
        cy *= image_height
        w *= image_width
        h *= image_height
    
        # Convert the center x, y, width, and height to xmin, ymin, xmax, ymax
        xmin = cx - w / 2
        ymin = cy - h / 2
        xmax = cx + w / 2
        ymax = cy + h / 2
    
        class_ids.append(class_id)
        bboxes.append((xmin, ymin, xmax, ymax))
        conf_scores.append(confidence)
    

    Display the results

    for class_id, bbox, conf in zip(class_ids, bboxes, conf_scores): print(f'Class ID: {class_id}, Confidence: {conf:.2f}, BBox coordinates: {bbox}')
    from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor sam_checkpoint = "/content/drive/MyDrive/yolov9/yolov9/sam_vit_h_4b8939.pth" model_type = "vit_h" sam = sam_model_registrymodel_type predictor = SamPredictor(sam)
    import cv2 image = cv2.cvtColor(cv2.imread('/content/drive/MyDrive/data/1.jpg'), cv2.COLOR_BGR2RGB) predictor.set_image(image)
    import matplotlib.patches as patches from matplotlib import pyplot as plt import numpy as np import yaml

    with open('/content/drive/MyDrive/yolov9/yolov9/data/coco.yaml', 'r') as file: coco_data = yaml.safe_load(file) class_names = coco_data['names']

    for class_id, bbox, conf in zip(class_ids, bboxes, conf_scores): class_name = class_names[class_id] # print(f'Class ID: {class_id}, Class Name: {class_name}, BBox coordinates: {bbox}')

    color_map = {} for class_id in class_ids: color_map[class_id] = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)

    def show_mask(mask, ax, color): h, w = mask.shape[-2:] mask_image = mask.reshape(h, w, 1) * np.array(color).reshape(1, 1, -1) ax.imshow(mask_image)

    def show_box(box, label, conf_score, color, ax): x0, y0 = box[0], box[1] w, h = box[2] - box[0], box[3] - box[1] rect = plt.Rectangle((x0, y0), w, h, edgecolor=color, facecolor='none', lw=2) ax.add_patch(rect)

    label_offset = 10
    
    # Construct the label with the class name and confidence score
    label_text = f'{label} {conf_score:.2f}'
    
    ax.text(x0, y0 - label_offset, label_text, color='black', fontsize=10, va='top', ha='left',
            bbox=dict(facecolor=color, alpha=0.7, edgecolor='none', boxstyle='square,pad=0.4'))
    

    plt.figure(figsize=(10, 10)) ax = plt.gca() plt.imshow(image)

    Display and process each bounding box with the corresponding mask

    for class_id, bbox in zip(class_ids, bboxes): class_name = class_names[class_id] # print(f'Class ID: {class_id}, Class Name: {class_name}, BBox coordinates: {bbox}')

    color = color_map[class_id]
    input_box = np.array(bbox)
    
    # Generate the mask for the current bounding box
    masks, _, _ = predictor.predict(
        point_coords=None,
        point_labels=None,
        box=input_box,
        multimask_output=False,
    )
    
    show_mask(masks[0], ax, color=color)
    show_box(bbox, class_name, conf, color, ax)
    

    Show the final plot

    plt.axis('off') plt.show()

  2. Assistant

    To encapsulate your code into a Gradio interface that allows users to interactively visualize the process and results you've shown, follow these steps. Ensure Gradio is installed in your environment (pip install gradio). The code you've given seems to process a given image, detects objects within it using YOLO, and then applies segmentation masks on those detected objects using SAM. Here's how you could set up a simple Gradio interface to run this pipeline interactively:

    1. Setup Gradio Interface:

      • Allow users to upload an image.
      • Display original image, detected bounding boxes with class names and confidence scores, and segmentation masks on selected objects.
    2. Function to Process Image:

      • This function will encapsulate the process you've written: reading an image, detecting objects, and then applying segmentation masks.
    import gradio as gr
    import cv2
    from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor
    import matplotlib.patches as patches
    from matplotlib import pyplot as plt
    import numpy as np
    import yaml
    
    # Load your model and other initialization code here
    sam_checkpoint = "/content/drive/MyDrive/yolov9/yolov9/sam_vit_h_4b8939.pth"
    model_type = "vit_h"
    sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)
    predictor = SamPredictor(sam)  
    with open('/content/drive/MyDrive/yolov9/yolov9/data/coco.yaml', 'r') as file:
        coco_data = yaml.safe_load(file)
        class_names = coco_data['names']
    
    def process_and_display(image_path):
        """
        Process the uploaded image and display results.
        """
        image = cv2.cvtColor(cv2.imread(image_path.name), cv2.COLOR_BGR2RGB)
        # Include your detection and segmentation process here
        # Replace this with your actual processing code
        # For demonstration, just displaying the uploaded image
        plt.figure(figsize=(10, 10))
        ax = plt.gca()
        plt.imshow(image)
        plt.axis('off')
        
        # You would insert the object detection, bounding box drawing, 
        # and segmentation mask overlay code here.
        
        # Save and return the result
        result_path = "result.jpg"
        plt.savefig(result_path)
        plt.close()
        return result_path
    
    # Gradio Interface
    inputs = gr.inputs.Image(type="filepath")
    outputs = gr.outputs.Image(type="file")
    
    iface = gr.Interface(fn=process_and_display, inputs=inputs, outputs=outputs, title="Object Detection and Segmentation")
    
    iface.launch()
    

    Note:

    • Replace the placeholder sections with your actual code for object detection, drawing bounding boxes, and overlaying segmentation masks.
    • Ensure your environment has all the necessary libraries (gradio, cv2, matplotlib, numpy, pyyaml, etc.) installed.
    • Adjust the file paths and names as necessary.
    • This code requires a graphical environment to display matplotlib plots. If running in a headless environment (e.g., some Docker containers), additional steps may be needed to handle display output (like using Agg backend for matplotlib).

    This setup provides a basic framework. Depending on your exact requirements, you may want to extend this with more interactive components or inputs (e.g., selecting a particular object detection model, tweaking detection thresholds, etc.).

  3. User

    tôi cần đầy đủ

  4. Assistant

    Để tạo một ứng dụng Gradio đầy đủ với chức năng bạn mô tả (phát hiện và phân đoạn đối tượng trên ảnh), chúng ta cần tích hợp tất cả các bước trong mã nguồn của bạn vào trong một hàm và sau đó sử dụng hàm đó trong giao diện Gradio. Tôi sẽ hướng dẫn bạn qua quá trình này từ đầu. Để rõ ràng, tôi sẽ mô giả thông tin đầu vào và kết quả đầu ra để chúng ta có thể tập trung vào việc tích hợp Gradio.

    Do mã nguồn bạn cung cấp bao gồm việc đọc thông tin nhãn phát hiện từ file, việc áp dụng mô hình SAM để phân đoạn và sau đó hiển thị kết quả, tôi sẽ giả sử bạn muốn người dùng tải lên một ảnh và một file nhãn tương ứng, sau đó hiển thị ảnh với các bounding box và phân đoạn bằng Gradio. Dưới đây là mã nguồn:

    Bước 1: Cài đặt Các Thư Viện Cần Thiết

    pip install gradio opencv-python-headless matplotlib numpy pyyaml
    

    Bước 2: Mã Nguồn Python Tích Hợp Gradio

    import gradio as gr
    import cv2
    from matplotlib import pyplot as plt
    import numpy as np
    import yaml
    import tempfile
    
    # Hàm để hiển thị mask và bounding box lên ảnh
    def show_detected_objects(image_path, detections_path):
        # Đọc ảnh và thông tin phát hiện từ file
        image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
        image_height, image_width, _ = image.shape
        
        bboxes = []  # Lưu thông tin bounding box
        class_ids = []  # Lưu ID của lớp
        conf_scores = []  # Lưu điểm tin cậy
        
        with open(detections_path, 'r') as file:
            for line in file:
                components = line.split()
                class_id = int(components[0])
                confidence = float(components[5])
                cx, cy, w, h = [float(x) for x in components[1:5]]
                
                # Chuyển đổi thành tọa độ thực trên ảnh
                cx *= image_width
                cy *= image_height
                w *= image_width
                h *= image_height
                
                bboxes.append([cx - w / 2, cy - h / 2, w, h])
                class_ids.append(class_id)
                conf_scores.append(confidence)
        
        # Hiển thị ảnh và các bounding box
        plt.figure()
        plt.imshow(image)
        for bbox in bboxes:
            rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=2, edgecolor='r', facecolor='none')
            plt.gca().add_patch(rect)
        
        # Lưu ảnh kết quả với bounding box vào một file tạm thời
        tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
        plt.savefig(tmp_file.name)
        plt.close()
        
        return tmp_file.name
    
    # Khởi tạo giao diện Gradio
    iface = gr.Interface(fn=show_detected_objects,
                         inputs=[gr.inputs.Image(label="Ảnh đầu vào", type="filepath"), 
                                 gr.inputs.Textbox(label="Đường dẫn đến file nhãn (labels)", type="str")],
                         outputs=[gr.outputs.Image(label="Kết quả")],
                         title="Phát Hiện và Phân Đoạn Đối Tượng")
                         
    iface.launch()
    

    Lưu ý:

    • Đoạn mã trên phụ thuộc vào cấu trúc và định dạng cụ thể của file nhãn bạn sử dụng.
    • detections_path trong giao diện được giả định là một chuỗi văn bản nhập vào và bạn cần đảm bảo đó là một đường dẫn hợp lệ tới file nhãn.
    • Điểm này trình bày một cách tiếp cận cơ bản và không bao gồm việc áp dụng mô hình SAM để phân đoạn vì việc tích hợp chính xác mô hình và tiến trình này phụ thuộc vào xử lý chính xác và hiệu quả của mô hình SAM, điều này nằm ngoài phạm vi câu trả lời.

    Hãy điều chỉnh theo nhu cầu cụ thể của ứng dụng và cấu trúc dữ liệu bạn đang làm việc.

  5. User

    AttributeError Traceback (most recent call last) in <cell line: 50>() 49 # Khởi tạo giao diện Gradio 50 iface = gr.Interface(fn=show_detected_objects, ---> 51 inputs=[gr.inputs.Image(label="Ảnh đầu vào", type="filepath"), 52 gr.inputs.Textbox(label="Đường dẫn đến file nhãn (labels)", type="str")], 53 outputs=[gr.outputs.Image(label="Kết quả")],

    AttributeError: module 'gradio' has no attribute 'inputs'

  6. Assistant

    Lỗi bạn gặp phát sinh bởi cách truy cập các đầu vào và đầu ra của Gradio không chính xác trong phiên bản mới nhất. Trong các bản Gradio gần đây, API đã được cập nhật và cách thiết lập đầu vào và đầu ra đã thay đổi. Để giải quyết lỗi này, bạn cần sử dụng cú pháp mới cho việc khởi tạo đầu vào và đầu ra. Dưới đây là cách sửa mã bằng cú pháp cập nhật:

    import gradio as gr
    import cv2
    from matplotlib import pyplot as plt
    import numpy as np
    import yaml
    import tempfile
    import os
    
    def show_detected_objects(image_path, detections_content):
        # Tạo một file tạm cho dữ liệu nhãn từ textarea
        _, detections_path = tempfile.mkstemp(suffix=".txt")
        with open(detections_path, 'w') as f:
            f.write(detections_content)
        
        # Đọc ảnh
        image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
        image_height, image_width, _ = image.shape
        
        bboxes = []  # Lưu thông tin bounding box
        class_ids = []  # Lưu ID của lớp
        conf_scores = []  # Lưu điểm tin cậy
        
        with open(detections_path, 'r') as file:
            for line in file:
                components = line.split()
                class_id = int(components[0])
                confidence = float(components[5])
                cx, cy, w, h = [float(x) for x in components[1:5]]
                
                # Chuyển đổi thành tọa độ thực trên ảnh
                cx *= image_width
                cy *= image_height
                w *= image_width
                h *= image_height
                
                bboxes.append([cx - w / 2, cy - h / 2, w, h])
                class_ids.append(class_id)
                conf_scores.append(confidence)
        
        # Hiển thị ảnh và các bounding box
        plt.figure(figsize=(10, 10))
        plt.imshow(image)
        for bbox in bboxes:
            rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=2, edgecolor='r', facecolor='none')
            plt.gca().add_patch(rect)
        
        # Lưu ảnh kết quả với bounding box vào một file tạm thời
        tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
        plt.savefig(tmp_file.name)
        plt.close()
        
        # Dọn dẹp file nhãn tạm
        os.remove(detections_path)
    
        return tmp_file.name
    
    # Khởi tạo giao diện Gradio
    iface = gr.Interface(fn=show_detected_objects,
                         inputs=[gr.inputs.Image(label="Ảnh đầu vào", tool="editor"), 
                                 gr.inputs.Textbox(label="Nội dung file nhãn (labels)", lines=7)],
                         outputs=gr.outputs.Image(label="Kết quả"),
                         title="Phát Hiện và Phân Đoạn Đối Tượng")
                         
    iface.launch()
    

    Trong phiên bản này, ta thay đổi cách xử lý đầu vào nhãn phát hiện. Thay vì yêu cầu đường dẫn đến file nhãn, giờ đây ta cho phép người dùng nhập trực tiếp nội dung nhãn vào một Textbox. Điều này giảm bớt rào cản về đường dẫn và làm cho ứng dụng dễ sử dụng hơn từ giao diện web của Gradio.

    Lưu ý về việc sử dụng gr.inputs.Textbox cho văn bản nhãn và gr.inputs.Image cho ảnh đầu vào. Đổi lại, các thành phần đầu ra và đầu vào được chỉ định một cách rõ ràng hơn với gr.inputs và gr.outputs không còn tồn tại trong cú pháp mới của Gradio; thay vào đó chúng ta khai báo trực tiếp loại đầu vào hoặc đầu ra mà chúng ta muốn sử dụng.

  7. User

    button_size = (100,50) with gr.Blocks() as demo: clicked_points = gr.State([]) origin_image = gr.State(None) click_mask = gr.State(None) features = gr.State(None) orig_h = gr.State(None) orig_w = gr.State(None) input_h = gr.State(None) input_w = gr.State(None)

    with gr.Row():
        with gr.Column(variant="panel"):
            with gr.Row():
                gr.Markdown("## Input Image")
            with gr.Row():
                # img = gr.Image(label="Input Image")
                source_image_click = gr.Image(
                    type="numpy",
                    height=300,
                    interactive=True,
                    label="Image: Upload an image and click the region you want to edit.",
                )
            with gr.Row():
                point_prompt = gr.Radio(
                    choices=["Foreground Point",
                                "Background Point"],
                    value="Foreground Point",
                    label="Point Label",
                    interactive=True,
                    show_label=False,
                )
                image_resolution = gr.Slider(
                    label="Image Resolution",
                    minimum=256,
                    maximum=768,
                    value=512,
                    step=64,
                )
                dilate_kernel_size = gr.Slider(label="Dilate Kernel Size", minimum=0, maximum=30, step=1, value=3)
        with gr.Column(variant="panel"):
            with gr.Row():
                gr.Markdown("## Control Panel")
            text_prompt = gr.Textbox(label="Text Prompt")
            lama = gr.Button("Inpaint Image", variant="primary")
            replace_sd = gr.Button("Replace Anything with SD", variant="primary")
            clear_button_image = gr.Button(value="Reset", every=None, variant="secondary")
    
    # todo: maybe we can delete this row, for it's unnecessary to show the original mask for customers
    with gr.Row(variant="panel"):
        with gr.Column():
            with gr.Row():
                gr.Markdown("## Mask")
            with gr.Row():
                click_mask = gr.Image(type="numpy", label="Click Mask")
        with gr.Column():
            with gr.Row():
                gr.Markdown("## Image Removed with Mask")
            with gr.Row():
                img_rm_with_mask = gr.Image(
                    type="numpy", label="Image Removed with Mask")
        with gr.Column():
            with gr.Row():
                gr.Markdown("## Replace Anything with Mask")
            with gr.Row():
                img_replace_with_mask = gr.Image(
                    type="numpy", label="Image Replace Anything with Mask")
    
    source_image_click.upload(
        image_upload,
        inputs=[source_image_click, image_resolution],
        outputs=[origin_image, features, orig_h, orig_w, input_h, input_w],
    )
    source_image_click.select(
        process_image_click,
        inputs=[origin_image, point_prompt,
                clicked_points, image_resolution,
                features, orig_h, orig_w, input_h, input_w],
        outputs=[source_image_click, clicked_points, click_mask],
        show_progress=True,
        queue=True,
    )
    
    # sam_mask.click(
    #     get_masked_img,
    #     [origin_image, w, h, features, orig_h, orig_w, input_h, input_w, dilate_kernel_size],
    #     [img_with_mask_0, img_with_mask_1, img_with_mask_2, mask_0, mask_1, mask_2]
    # )
    
    lama.click(
        get_inpainted_img,
        [origin_image, click_mask, image_resolution],
        [img_rm_with_mask]
    )
    
    replace_sd.click(
        get_replace_img_with_sd,
        [origin_image, click_mask, image_resolution, text_prompt],
        [img_replace_with_mask]
    )
    
    
    def reset(*args):
        return [None for _ in args]
    
    clear_button_image.click(
        reset,
        [origin_image, features, click_mask, img_rm_with_mask, img_replace_with_mask],
        [origin_image, features, click_mask, img_rm_with_mask, img_replace_with_mask]
    )
    

    if name == "main": demo.queue(api_open=False).launch(server_name='0.0.0.0', share=False, debug=True)

  8. Assistant

    Your code sample shows how to structure an advanced Gradio interface using the gr.Blocks API to incorporate image processing and manipulation tasks with interactive elements like clicks on the image, sliders, and buttons for different processing functions. This setup allows for an interactive experience where users can upload an image, define areas of interest or parts to modify by clicking, and use the specified functionality (e.g., inpainting or object replacement).

    However, your code sample seems to have placeholders for actual processing functions (image_upload, process_image_click, get_inpainted_img, get_replace_img_with_sd, and reset). For the code to run, you'll need to define these functions with the appropriate logic for handling image processing based on user inputs.

    Here's a simplified breakdown of what your current Gradio Blocks setup aims to achieve and some important points for each part:

    1. State Management: Using gr.State to keep track of various aspects like clicked points, the original image, and the current click mask throughout the session.

    2. Interactive Image Upload and Edit:

      • source_image_click is set up for users to upload and click on regions within an uploaded image.
      • Click events need to be processed by a function (process_image_click) that you'll need to define.
      • The resolution and dilation settings are adjustable via sliders.
    3. Processing Buttons:

      • lama button to perform image inpainting on the selected region.
      • replace_sd for replacing the selected area with specified characteristics (likely using a generative model).
      • Both these buttons rely on functions (get_inpainted_img, get_replace_img_with_sd) that should contain the logic for processing the image as per the user's input.
    4. Reset Functionality: A basic reset function template (reset) is suggested but needs to be fully implemented to clear the session states effectively.

    5. Visualization: Apart from processing, the interface includes sections to visualize masks and modified images, providing instant feedback on the applied changes.

    To make your code operational, here's a generic outline of what those missing function definitions might look like, using process_image_click as an example (note: actual implementations will vary based on your specific processing logic):

    def process_image_click(original_image, point_label, clicked_points, image_resolution, features, orig_h, orig_w, input_h, input_w):
        # Placeholder: Add logic to process the image based on clicked points, etc.
        # This function should modify the image or generate masks as required and return the updated image, updated clicked_points state, and any new mask generated.
        updated_image = original_image  # Placeholder for processed image
        new_click_mask = None  # Placeholder for new click mask generation
        return updated_image, clicked_points, new_click_mask
    

    For your Gradio interface to work as intended, you need to:

    • Implement Processing Functions: Define the logic inside image_upload, process_image_click, get_inpainted_img, get_replace_img_with_sd, and reset according to your requirements.
    • Ensure Input and Output Matching: Each component and function must correctly match expected inputs and outputs, especially in complex interactive elements.
    • Handle File Paths and Types Appropriately: When dealing with file paths or specific data types (e.g., Numpy arrays), ensure your functions handle these correctly, especially when reading, processing, and outputting images.

    Given the advanced nature of your interface, it's essential to iteratively develop and test each part of your application, starting with individual processing functions and gradually integrating them into the Gradio Blocks setup for a seamless user experience.

  9. User

    làm gradio cho code def show_detected_objects(image_path, detections_path): # Đọc ảnh và thông tin phát hiện từ file image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB) image_height, image_width, _ = image.shape

    bboxes = []  # Lưu thông tin bounding box
    class_ids = []  # Lưu ID của lớp
    conf_scores = []  # Lưu điểm tin cậy
    
    with open(detections_path, 'r') as file:
        for line in file:
            components = line.split()
            class_id = int(components[0])
            confidence = float(components[5])
            cx, cy, w, h = [float(x) for x in components[1:5]]
            
            # Chuyển đổi thành tọa độ thực trên ảnh
            cx *= image_width
            cy *= image_height
            w *= image_width
            h *= image_height
            
            bboxes.append([cx - w / 2, cy - h / 2, w, h])
            class_ids.append(class_id)
            conf_scores.append(confidence)
    
    # Hiển thị ảnh và các bounding box
    plt.figure()
    plt.imshow(image)
    for bbox in bboxes:
        rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=2, edgecolor='r', facecolor='none')
        plt.gca().add_patch(rect)
    
    # Lưu ảnh kết quả với bounding box vào một file tạm thời
    tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
    plt.savefig(tmp_file.name)
    plt.close()
    
    return tmp_file.name
    
  10. Assistant

    Để tạo một ứng dụng Gradio dựa trên hàm show_detected_objects bạn đã cung cấp, chúng ta sẽ tiến hành các bước sau:

    1. Cài đặt Gradio: Đảm bảo bạn đã cài đặt thư viện Gradio. Nếu chưa, bạn có thể cài đặt nó bằng lệnh pip install gradio.
    2. Xây dựng Giao Diện Gradio: Tạo một giao diện đơn giản cho phép người dùng tải lên một ảnh và một file văn bản chứa thông tin các bounding box.
    3. Hiển Thị Ảnh với Bounding Box: Sau khi người dùng tải lên ảnh và file nhãn, hàm show_detected_objects sẽ được gọi để xử lý và trả về ảnh kết quả với bounding box.

    Dưới đây là mã nguồn minh họa:

    import gradio as gr
    import cv2
    from matplotlib import pyplot as plt
    import numpy as np
    import tempfile
    import os
    
    def show_detected_objects(image_path, detections_content):
        # Đọc ảnh
        image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2RGB)
        image_height, image_width, _ = image.shape
        
        bboxes = []  # Lưu thông tin bounding box
        class_ids = []  # Lưu ID của lớp
        conf_scores = []  # Lưu điểm tin cậy
        
        # Tạo một file tạm từ nội dung nhập
        _, detections_path = tempfile.mkstemp(suffix=".txt")
        with open(detections_path, 'w') as f:
            f.write(detections_content)
        
        with open(detections_path, 'r') as file:
            for line in file:
                components = line.split()
                class_id = int(components[0])
                confidence = float(components[5])
                cx, cy, w, h = [float(x) for x in components[1:5]]
                
                # Chuyển đổi thành tọa độ thực trên ảnh
                cx *= image_width
                cy *= image_height
                w *= image_width
                h *= image_height
                
                bboxes.append([cx - w / 2, cy - h / 2, w, h])
                class_ids.append(class_id)
                conf_scores.append(confidence)
        
        # Hiển thị ảnh và các bounding box
        plt.figure(figsize=(10, 10))
        plt.imshow(image)
        for bbox in bboxes:
            rect = plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], linewidth=2, edgecolor='r', facecolor='none')
            plt.gca().add_patch(rect)
        
        # Lưu ảnh kết quả với bounding box vào một file tạm thời
        tmp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.jpg')
        plt.savefig(tmp_file.name)
        plt.close()
        
        # Dọn dẹp file nhãn tạm
        os.remove(detections_path)
    
        return tmp_file.name
    
    # Xây dựng giao diện Gradio
    iface = gr.Interface(
        fn=show_detected_objects,
        inputs=[gr.inputs.Image(type="filepath", label="Ảnh Đầu Vào"), gr.inputs.Textbox(label="Nội Dung File Nhãn", lines=7)],
        outputs=gr.outputs.Image(type="file", label="Ảnh Kết Quả"),
        title="Hiển Thị Bounding Box Trên Ảnh"
    )
    
    if __name__ == "__main__":
        iface.launch()
    

    Đoạn mã trên tạo một giao diện Gradio cho phép người dùng tải lên một ảnh và nhập nội dung của file nhãn (detections_content) trực tiếp qua một Textbox. Sau đó, hàm show_detected_objects sẽ đọc ảnh, tạo một file tạm từ nội dung nhãn được người dùng nhập, xử lý và trả về ảnh với bounding box đã được vẽ. Cuối cùng, giao diện hiển thị ảnh kết quả cho người dùng.