CoolFace
Apppublic

MLBench/Coin_Detection

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
app.py245 linesDownload Raw Back to root
1# import gradio as gr2# from ultralytics import YOLO3# import os4# import torch5 6# # --- DOCUMENTATION STRINGS (Coin Detector App) ---7 8# GUIDELINE_SETUP = """9# ## 1. Quick Start Guide: Detection and Filtering10 11# This application uses a trained YOLO model to automatically detect coins in an image and allows you to filter the results based on detection confidence.12 13# 1.  **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.14# 2.  **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.15# 3.  **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.16# """17 18# GUIDELINE_INPUT = """19# ## 2. Expected Inputs and Parameters20 21# | Input Field | Purpose | Requirement |22# | :--- | :--- | :--- |23# | **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |24# | **Confidence Threshold** | Filters the model's predictions. Only detections with a confidence score equal to or higher than this value will be shown. | Slider range: 0.0 (least strict) to 1.0 (most strict). Default is 0.5. |25 26# **Tip:** If you see too many false positives (non-coins being detected), raise the threshold. If the model misses coins you know are there, try lowering the threshold.27# """28 29# GUIDELINE_OUTPUT = """30# ## 3. Expected Outputs (Annotated Image)31 32# The output is a single image component displaying the **Annotated Frame**.33 34# *   **Content:** This image is the original input image with colored bounding boxes drawn around every coin detected by the model that passed the `Confidence Threshold` filter.35# *   **Bounding Boxes:** Each box confirms a coin detection and is usually accompanied by a label (e.g., 'coin') and the confidence score (e.g., 0.95).36# """37 38# # Load the YOLO model39# # NOTE: The model file 'best1.pt' must exist in the same directory or accessible path.40# model = YOLO('best1.pt')41 42# def predict(img, confidence_threshold):43#     # Perform inference44#     # Note: Using verbose=False to keep the interface clean during prediction45#     results = model(img, verbose=False) 46    47#     # Filter predictions based on the confidence threshold48#     # The results[0].boxes.data contains the detection results, including confidence scores49    50#     # We filter the bounding boxes data array based on the confidence score (index 4)51#     # Then we must convert the filtered list back to a tensor format expected by the plotting function.52    53#     filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]54    55#     if filtered_data:56#         filtered_tensor = torch.stack(filtered_data)57        58#         # Create a deep copy of the original results object to manipulate its boxes data59#         filtered_results = results[0].cpu()60#         filtered_results.boxes.data = filtered_tensor61        62#         # Plot the results using the filtered results object63#         annotated_frame = filtered_results.plot()64#     else:65#         # If no coins pass the filter, plot the original image without boxes66#         annotated_frame = results[0].plot()67        68#     return annotated_frame69 70# # Create the Gradio interface using gr.Blocks to allow for documentation placement71# with gr.Blocks(title="Coin Detector") as iface:72    73#     gr.Markdown("# Coin Detector")74#     gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")75    76#     # 1. Guidelines Section77#     with gr.Accordion("User Guidelines and Documentation", open=False):78#         gr.Markdown(GUIDELINE_SETUP)79#         gr.Markdown("---")80#         gr.Markdown(GUIDELINE_INPUT)81#         gr.Markdown("---")82#         gr.Markdown(GUIDELINE_OUTPUT)83        84#     gr.Markdown("---")85 86#     # 2. Input/Output Layout87#     with gr.Row():88#         with gr.Column(scale=2):89#             gr.Markdown("## Step 1: Upload an Image ")90#             input_img = gr.Image(label="Input Image", type="filepath")91#             gr.Markdown("## Step 2: Adjest Confidence Threshold (Optional) ")92#             confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)93#             gr.Markdown("## Step 3: Click Detect Coins ")94#             submit_btn = gr.Button("Detect Coins", variant="primary")95            96#         with gr.Column(scale=1):97#             gr.Markdown("## Result ")98#             output_img = gr.Image(label="Output Image")99 100#     # 3. Example Data (if available, added here for completeness)101#     # Note: Since no examples were provided, this is commented out or left as placeholders.102#     gr.Markdown("## Examples ")103#     gr.Examples(104#         examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],105#         inputs=[input_img, confidence_slider],106#         outputs=output_img,107#         fn=predict,108#         cache_examples=False109#     )110 111#     # 4. Event Handler112#     submit_btn.click(113#         fn=predict,114#         inputs=[input_img, confidence_slider],115#         outputs=output_img116#     )117 118# # Launch the Gradio interface119# iface.queue()120# iface.launch(share=True)121 122 123 124import gradio as gr125from ultralytics import YOLO126import torch 127import os128 129# --- DOCUMENTATION STRINGS (Coin Detector App) ---130 131GUIDELINE_SETUP = """132## 1. Quick Start Guide: Detection and Filtering133 134This application uses a trained YOLO model to automatically detect coins in an image and allows you to filter the results based on detection confidence.135 1361.  **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.1372.  **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.1383.  **Run:** Click the **"Detect Coins"** button.1394.  **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.140"""141 142GUIDELINE_INPUT = """143## 2. Expected Inputs and Parameters144 145| Input Field | Purpose | Requirement |146| :--- | :--- | :--- |147| **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |148| **Confidence Threshold** | Filters the model's predictions. Only detections with a confidence score equal to or higher than this value will be shown. | Slider range: 0.0 (least strict) to 1.0 (most strict). Default is 0.5. |149 150**Tip:** If you see too many false positives (non-coins being detected), raise the threshold. If the model misses coins you know are there, try lowering the threshold.151"""152 153GUIDELINE_OUTPUT = """154## 3. Expected Outputs (Annotated Image)155 156The output is a single image component displaying the **Annotated Frame**.157 158*   **Content:** This image is the original input image with colored bounding boxes drawn around every coin detected by the model that passed the `Confidence Threshold` filter.159*   **Bounding Boxes:** Each box confirms a coin detection and is usually accompanied by a label (e.g., 'coin') and the confidence score (e.g., 0.95).160"""161 162# Load the YOLO model163model = YOLO('best1.pt')164 165def predict(img, confidence_threshold):166    # Perform inference167    # Using verbose=False to suppress unnecessary console output during inference168    results = model(img, verbose=True) 169    170    # We filter the bounding boxes data array based on the confidence score (index 4)171    # Filter predictions based on the confidence threshold172    filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]173    174    if filtered_data:175        # Stack the filtered tensors back into a single tensor176        filtered_tensor = torch.stack(filtered_data)177        178        # Create a results object to plot only the filtered boxes179        filtered_results = results[0].cpu()180        filtered_results.boxes.data = filtered_tensor181        182        # Plot the results using the filtered results object183        annotated_frame = filtered_results.plot()184    else:185        # If no coins pass the filter, plot the original image without boxes186        annotated_frame = results[0].plot()187        188    return annotated_frame189 190# Create the Gradio interface using gr.Blocks to allow for documentation placement191with gr.Blocks(title="Coin Detector") as iface:192    193    gr.Markdown("# Coin Detector")194    gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")195    196    # 1. Guidelines Section197    with gr.Accordion("User Guidelines and Documentation", open=False):198        gr.Markdown(GUIDELINE_SETUP)199        gr.Markdown("---")200        gr.Markdown(GUIDELINE_INPUT)201        gr.Markdown("---")202        gr.Markdown(GUIDELINE_OUTPUT)203        204    gr.Markdown("---")205 206    # 2. Input/Output Layout207    with gr.Row():208        with gr.Column(scale=1):209            gr.Markdown("## Step 1: Upload an Image Having Coin")210            input_img = gr.Image(label="Input Image", type="filepath")211            gr.Markdown("## Step 2: Set the Confidence Threshold (Optional) ")212            confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)213            gr.Markdown("## Step 3: Click Detect Coins Button")214            submit_btn = gr.Button("Detect Coins", variant="primary")215            216        with gr.Column(scale=2):217            gr.Markdown("## Result ")218            output_img = gr.Image(label="Detected Coins ")219 220 221    # 3. Example Data (if available, added here for completeness)222    # Note: Since no examples were provided, this is commented out or left as placeholders.223    gr.Markdown("## Examples ")224    gr.Examples(225        examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],226        inputs=[input_img, confidence_slider],227        outputs=output_img,228        fn=predict,229        cache_examples=False230    )231 232    # 3. Event Handler233    submit_btn.click(234        fn=predict,235        inputs=[input_img, confidence_slider],236        outputs=output_img237    )238 239# Launch the Gradio interface240iface.queue()241iface.launch(242    server_name="0.0.0.0",243    server_port=7860,244    share=True245)