Coin_Detection / app.py
muhammadhamza-stack
update app.py
38d3d04
# import gradio as gr
# from ultralytics import YOLO
# import os
# import torch
# # --- DOCUMENTATION STRINGS (Coin Detector App) ---
# GUIDELINE_SETUP = """
# ## 1. Quick Start Guide: Detection and Filtering
# 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.
# 1. **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.
# 2. **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.
# 3. **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.
# """
# GUIDELINE_INPUT = """
# ## 2. Expected Inputs and Parameters
# | Input Field | Purpose | Requirement |
# | :--- | :--- | :--- |
# | **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |
# | **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. |
# **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.
# """
# GUIDELINE_OUTPUT = """
# ## 3. Expected Outputs (Annotated Image)
# The output is a single image component displaying the **Annotated Frame**.
# * **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.
# * **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).
# """
# # Load the YOLO model
# # NOTE: The model file 'best1.pt' must exist in the same directory or accessible path.
# model = YOLO('best1.pt')
# def predict(img, confidence_threshold):
# # Perform inference
# # Note: Using verbose=False to keep the interface clean during prediction
# results = model(img, verbose=False)
# # Filter predictions based on the confidence threshold
# # The results[0].boxes.data contains the detection results, including confidence scores
# # We filter the bounding boxes data array based on the confidence score (index 4)
# # Then we must convert the filtered list back to a tensor format expected by the plotting function.
# filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]
# if filtered_data:
# filtered_tensor = torch.stack(filtered_data)
# # Create a deep copy of the original results object to manipulate its boxes data
# filtered_results = results[0].cpu()
# filtered_results.boxes.data = filtered_tensor
# # Plot the results using the filtered results object
# annotated_frame = filtered_results.plot()
# else:
# # If no coins pass the filter, plot the original image without boxes
# annotated_frame = results[0].plot()
# return annotated_frame
# # Create the Gradio interface using gr.Blocks to allow for documentation placement
# with gr.Blocks(title="Coin Detector") as iface:
# gr.Markdown("# Coin Detector")
# gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")
# # 1. Guidelines Section
# with gr.Accordion("User Guidelines and Documentation", open=False):
# gr.Markdown(GUIDELINE_SETUP)
# gr.Markdown("---")
# gr.Markdown(GUIDELINE_INPUT)
# gr.Markdown("---")
# gr.Markdown(GUIDELINE_OUTPUT)
# gr.Markdown("---")
# # 2. Input/Output Layout
# with gr.Row():
# with gr.Column(scale=2):
# gr.Markdown("## Step 1: Upload an Image ")
# input_img = gr.Image(label="Input Image", type="filepath")
# gr.Markdown("## Step 2: Adjest Confidence Threshold (Optional) ")
# confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)
# gr.Markdown("## Step 3: Click Detect Coins ")
# submit_btn = gr.Button("Detect Coins", variant="primary")
# with gr.Column(scale=1):
# gr.Markdown("## Result ")
# output_img = gr.Image(label="Output Image")
# # 3. Example Data (if available, added here for completeness)
# # Note: Since no examples were provided, this is commented out or left as placeholders.
# gr.Markdown("## Examples ")
# gr.Examples(
# examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],
# inputs=[input_img, confidence_slider],
# outputs=output_img,
# fn=predict,
# cache_examples=False
# )
# # 4. Event Handler
# submit_btn.click(
# fn=predict,
# inputs=[input_img, confidence_slider],
# outputs=output_img
# )
# # Launch the Gradio interface
# iface.queue()
# iface.launch(share=True)
import gradio as gr
from ultralytics import YOLO
import torch
import os
# --- DOCUMENTATION STRINGS (Coin Detector App) ---
GUIDELINE_SETUP = """
## 1. Quick Start Guide: Detection and Filtering
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.
1. **Upload Image:** Upload the image you want to analyze in the 'Input Image' box.
2. **Adjust Threshold:** Use the 'Confidence Threshold' slider to set the minimum certainty required for a coin to be displayed.
3. **Run:** Click the **"Detect Coins"** button.
4. **Review:** The output image will show bounding boxes around all detections that meet or exceed the set threshold.
"""
GUIDELINE_INPUT = """
## 2. Expected Inputs and Parameters
| Input Field | Purpose | Requirement |
| :--- | :--- | :--- |
| **Input Image** | The photograph containing the coins you wish to detect. | Must be an image file (e.g., JPG, PNG). |
| **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. |
**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.
"""
GUIDELINE_OUTPUT = """
## 3. Expected Outputs (Annotated Image)
The output is a single image component displaying the **Annotated Frame**.
* **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.
* **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).
"""
# Load the YOLO model
model = YOLO('best1.pt')
def predict(img, confidence_threshold):
# Perform inference
# Using verbose=False to suppress unnecessary console output during inference
results = model(img, verbose=True)
# We filter the bounding boxes data array based on the confidence score (index 4)
# Filter predictions based on the confidence threshold
filtered_data = [box.cpu() for box in results[0].boxes.data if box[4] >= confidence_threshold]
if filtered_data:
# Stack the filtered tensors back into a single tensor
filtered_tensor = torch.stack(filtered_data)
# Create a results object to plot only the filtered boxes
filtered_results = results[0].cpu()
filtered_results.boxes.data = filtered_tensor
# Plot the results using the filtered results object
annotated_frame = filtered_results.plot()
else:
# If no coins pass the filter, plot the original image without boxes
annotated_frame = results[0].plot()
return annotated_frame
# Create the Gradio interface using gr.Blocks to allow for documentation placement
with gr.Blocks(title="Coin Detector") as iface:
gr.Markdown("# Coin Detector")
gr.Markdown("Upload an image to detect coins. Adjust the confidence threshold to filter results.")
# 1. Guidelines Section
with gr.Accordion("User Guidelines and Documentation", open=False):
gr.Markdown(GUIDELINE_SETUP)
gr.Markdown("---")
gr.Markdown(GUIDELINE_INPUT)
gr.Markdown("---")
gr.Markdown(GUIDELINE_OUTPUT)
gr.Markdown("---")
# 2. Input/Output Layout
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("## Step 1: Upload an Image Having Coin")
input_img = gr.Image(label="Input Image", type="filepath")
gr.Markdown("## Step 2: Set the Confidence Threshold (Optional) ")
confidence_slider = gr.Slider(minimum=0, maximum=1, value=0.5, label="Confidence Threshold", step=0.01)
gr.Markdown("## Step 3: Click Detect Coins Button")
submit_btn = gr.Button("Detect Coins", variant="primary")
with gr.Column(scale=2):
gr.Markdown("## Result ")
output_img = gr.Image(label="Detected Coins ")
# 3. Example Data (if available, added here for completeness)
# Note: Since no examples were provided, this is commented out or left as placeholders.
gr.Markdown("## Examples ")
gr.Examples(
examples=[["./sample_data/coin.jpeg", 0.5], ["./sample_data/Test21.png", 0.4]],
inputs=[input_img, confidence_slider],
outputs=output_img,
fn=predict,
cache_examples=False
)
# 3. Event Handler
submit_btn.click(
fn=predict,
inputs=[input_img, confidence_slider],
outputs=output_img
)
# Launch the Gradio interface
iface.queue()
iface.launch(
server_name="0.0.0.0",
server_port=7860,
share=True
)