Saini16/Blood_Cell_Object_Detection
1
1import streamlit as st2from PIL import Image, ImageDraw3import io4import os5import numpy as np6import tempfile7 8# Set page config9st.set_page_config(10 page_title="BCCD Object Detection with YOLOv10",11 page_icon="🔍",12 layout="wide"13)14 15# Initialize session state variables if they don't exist16if 'model' not in st.session_state:17 st.session_state.model = None18if 'class_names' not in st.session_state:19 st.session_state.class_names = ['RBC', 'WBC', 'Platelets'] # Classes in BCCD dataset20 21# Mock function to demo the app without dependencies22@st.cache_resource23def get_model():24 """This is a mock function to demonstrate the UI without actual model loading."""25 return "mock_model"26 27def main():28 st.title("Blood Cell Object Detection with YOLOv10")29 st.markdown("""30 This application uses a YOLOv10 model fine-tuned on the BCCD (Blood Cell Count Dataset) 31 to detect three types of blood cells: Red Blood Cells (RBC), White Blood Cells (WBC), and Platelets.32 """)33 34 # Sidebar for model information and controls35 with st.sidebar:36 st.header("About")37 st.markdown("""38 - **Model**: YOLOv1039 - **Dataset**: BCCD (Blood Cell Count Dataset)40 - **Classes**: RBC, WBC, Platelets41 """)42 43 st.header("Instructions")44 st.markdown("""45 1. Upload an image of blood cells46 2. The model will detect and classify blood cells47 3. Results will show bounding boxes and detection metrics48 """)49 50 st.header("Model Confidence Threshold")51 confidence_threshold = st.slider("Confidence Threshold", 0.1, 0.9, 0.5, 0.05)52 53 st.header("Model File (Optional)")54 model_file = st.file_uploader("Upload custom model file (*.pt)", type=["pt"])55 56 if model_file:57 st.success("Custom model loaded successfully!")58 59 # Set mock model for demo60 st.session_state.model = get_model()61 62 # File upload63 uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])64 65 if uploaded_file is not None:66 # Read and display the uploaded image67 image_bytes = uploaded_file.read()68 image = Image.open(io.BytesIO(image_bytes))69 70 col1, col2 = st.columns(2)71 72 with col1:73 st.subheader("Original Image")74 st.image(image, use_column_width=True)75 76 # Mock detection process for demo purposes77 with col2:78 st.subheader("Detection Results (Demo)")79 # Generate a demo image with bounding boxes80 # In a real implementation, this would use actual detection results81 draw_image = image.copy()82 draw = ImageDraw.Draw(draw_image)83 84 # Mock bounding boxes for demo (simulated detections)85 # Format: [x1, y1, x2, y2, class_id, confidence]86 mock_detections = [87 [50, 50, 100, 100, 0, 0.92], # RBC88 [150, 75, 200, 125, 0, 0.88], # RBC89 [120, 200, 220, 300, 1, 0.94], # WBC90 [300, 150, 320, 170, 2, 0.85], # Platelet91 [250, 220, 270, 240, 2, 0.79] # Platelet92 ]93 94 # Draw bounding boxes95 class_colors = {96 0: (255, 0, 0, 128), # RBC - Red (semi-transparent)97 1: (0, 0, 255, 128), # WBC - Blue (semi-transparent)98 2: (0, 255, 0, 128) # Platelets - Green (semi-transparent)99 }100 101 class_names = {102 0: "RBC",103 1: "WBC",104 2: "Platelet"105 }106 107 # Draw each detection108 for det in mock_detections:109 x1, y1, x2, y2, class_id, conf = det110 111 # Draw rectangle112 draw.rectangle([x1, y1, x2, y2], outline=class_colors[class_id][:3], width=2)113 114 # Add label with confidence115 label = f"{class_names[class_id]} {conf:.2f}"116 draw.text((x1, y1-15), label, fill=class_colors[class_id][:3])117 118 st.image(draw_image, use_column_width=True)119 st.caption("Demo visualization with simulated detections")120 121 # Show mock statistics122 st.subheader("Detection Statistics (Sample Data)")123 124 # Mock detection counts125 st.markdown("### Detection Counts")126 st.markdown("- **RBC**: 120")127 st.markdown("- **WBC**: 8")128 st.markdown("- **Platelets**: 30")129 130 # Display mock confidence metrics131 st.markdown("### Confidence Metrics")132 metrics_data = [133 {134 "Class": "RBC",135 "Count": 120,136 "Avg Confidence": "0.85",137 "Max Confidence": "0.95",138 "Min Confidence": "0.72"139 },140 {141 "Class": "WBC",142 "Count": 8,143 "Avg Confidence": "0.91",144 "Max Confidence": "0.98",145 "Min Confidence": "0.82"146 },147 {148 "Class": "Platelets",149 "Count": 30,150 "Avg Confidence": "0.78",151 "Max Confidence": "0.89",152 "Min Confidence": "0.65"153 }154 ]155 156 st.table(metrics_data)157 158 # Add precision and recall table159 st.markdown("### Precision and Recall Metrics")160 precision_recall_data = [161 {162 "Class": "All Classes",163 "Precision": "0.89",164 "Recall": "0.91",165 "F1-Score": "0.90",166 "IoU": "0.82"167 },168 {169 "Class": "RBC",170 "Precision": "0.92",171 "Recall": "0.94",172 "F1-Score": "0.93",173 "IoU": "0.86"174 },175 {176 "Class": "WBC",177 "Precision": "0.87",178 "Recall": "0.85",179 "F1-Score": "0.86",180 "IoU": "0.79"181 },182 {183 "Class": "Platelets",184 "Precision": "0.84",185 "Recall": "0.81",186 "F1-Score": "0.82",187 "IoU": "0.75"188 }189 ]190 191 st.table(precision_recall_data)192 193 # Add explanation of metrics194 with st.expander("About Precision and Recall Metrics"):195 st.markdown("""196 - **Precision**: The proportion of positive identifications that were actually correct. Formula: TP/(TP+FP)197 - **Recall**: The proportion of actual positives that were identified correctly. Formula: TP/(TP+FN)198 - **F1-Score**: The harmonic mean of precision and recall, providing a balance between the two. Formula: 2*(Precision*Recall)/(Precision+Recall)199 - **IoU (Intersection over Union)**: Measures the overlap between the predicted bounding box and the ground truth bounding box.200 201 *These metrics are crucial for evaluating the performance of object detection models. Higher values indicate better performance.*202 """)203 204 # Add information about training205 st.markdown("---")206 st.subheader("Model Training Information")207 st.markdown("""208 The YOLOv10 model used in this application was fine-tuned on the BCCD dataset. 209 To see the fine-tuning process or train your own model, check the `train_yolov10.py` file 210 included in the repository.211 212 The BCCD dataset contains images of blood cells with annotations for:213 - Red Blood Cells (RBC)214 - White Blood Cells (WBC)215 - Platelets216 """)217 218if __name__ == "__main__":219 main()220 