File size: 15,713 Bytes
34d2ee5
71b736f
34d2ee5
71b736f
 
 
 
34d2ee5
 
 
40c6797
34d2ee5
40c6797
 
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71b736f
 
 
34d2ee5
 
71b736f
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c6797
34d2ee5
 
 
 
 
40c6797
34d2ee5
 
40c6797
34d2ee5
 
 
 
 
40c6797
34d2ee5
 
 
40c6797
34d2ee5
 
40c6797
 
34d2ee5
 
40c6797
34d2ee5
40c6797
 
 
 
 
34d2ee5
 
 
 
 
40c6797
34d2ee5
 
40c6797
34d2ee5
 
 
 
 
 
40c6797
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c6797
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c6797
34d2ee5
40c6797
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40c6797
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
3cdf023
 
4011c92
 
3cdf023
 
8dbd3b3
34d2ee5
 
8dbd3b3
34d2ee5
3cdf023
 
 
34d2ee5
 
 
 
 
 
 
 
40c6797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d2ee5
 
40c6797
34d2ee5
 
 
 
 
 
 
40c6797
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d2ee5
 
 
8dbd3b3
34d2ee5
 
 
 
 
 
 
 
 
 
40c6797
 
 
 
34d2ee5
 
71b736f
34d2ee5
71b736f
34d2ee5
71b736f
 
34d2ee5
 
40c6797
 
71b736f
40c6797
 
 
71b736f
34d2ee5
 
 
71b736f
40c6797
71b736f
40c6797
 
 
71b736f
 
 
 
 
 
40c6797
 
 
 
 
34d2ee5
71b736f
34d2ee5
 
 
 
 
 
 
 
 
40c6797
 
 
34d2ee5
 
71b736f
 
 
 
 
 
34d2ee5
 
40c6797
34d2ee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""
YOLOv8 Traffic Bird's Eye View Detection Application

This application provides a web-based interface for traffic object detection using 
a specialized YOLOv8 model trained on aerial/bird's eye view imagery.
Users can upload aerial images or select from examples to receive real-time 
traffic detection results with visual annotations and structured data output.
"""

import logging
import os
import sys
import tempfile
from datetime import datetime
from typing import Tuple, Optional

import cv2
import gradio as gr
import numpy as np
import pandas as pd
from PIL import Image
from ultralytics import YOLO

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Global model instance
model: Optional[YOLO] = None


def initialize_model() -> bool:
    """
    Initialize YOLOv8 model with error handling and validation.

    Returns:
        bool: True if model loaded successfully, False otherwise
    """
    global model
    try:
        logger.info("Loading traffic bird's eye view YOLOv8 model...")
        model = YOLO("./traffic_birdseye.pt")
        logger.info("Traffic bird's eye view YOLOv8 model loaded successfully")
        return True
    except Exception as e:
        logger.error("Failed to load traffic bird's eye view YOLOv8 model: %s", str(e))
        model = None
        return False


def preprocess_image(image: Image.Image) -> np.ndarray:
    """
    Convert PIL Image to NumPy array for YOLOv8 processing.

    Args:
        image (Image.Image): PIL Image object

    Returns:
        np.ndarray: NumPy array in RGB format
    """
    try:
        # Convert PIL Image to RGB if not already
        if image.mode != 'RGB':
            image = image.convert('RGB')

        # Convert to NumPy array
        image_array = np.array(image)

        logger.info("Image preprocessed: shape %s", image_array.shape)
        return image_array

    except Exception as e:
        logger.error("Error preprocessing image: %s", str(e))
        raise


def detect_objects(image: Image.Image, conf_threshold: float = 0.25) -> Tuple[Image.Image, pd.DataFrame, str]:
    """
    Main object detection function that processes images through YOLOv8.

    Args:
        image (Image.Image): PIL Image object to process
        conf_threshold (float): Confidence threshold for filtering detections (0.0 to 1.0)

    Returns:
        Tuple[Image.Image, pd.DataFrame, str]: Annotated image, detection results table, and CSV file path
    """
    if model is None:
        logger.error("YOLOv8 model not loaded")
        # Return original image and empty dataframe
        empty_df = pd.DataFrame(columns=['class', 'confidence', 'x1', 'y1', 'x2', 'y2'])
        return image, empty_df, None

    try:
        # Preprocess the image
        logger.info("Starting object detection with confidence threshold: %.2f", conf_threshold)
        processed_image = preprocess_image(image)

        # Run YOLOv8 inference with confidence threshold
        results = model(processed_image, conf=conf_threshold)

        # Parse detection results
        annotated_image, detection_data = parse_detection_results(results[0], image, conf_threshold)

        # Create CSV file for download
        csv_file_path = create_csv_download(detection_data, conf_threshold)

        logger.info("Object detection completed successfully with %d detections", len(detection_data))
        return annotated_image, detection_data, csv_file_path

    except Exception as e:
        logger.error("Error during object detection: %s", str(e))
        # Return original image and empty dataframe on error
        empty_df = pd.DataFrame(columns=['class', 'confidence', 'x1', 'y1', 'x2', 'y2'])
        return image, empty_df, None


def parse_detection_results(results, original_image: Image.Image, conf_threshold: float = 0.25) -> Tuple[Image.Image, pd.DataFrame]:
    """
    Parse YOLOv8 detection results to extract classes, confidence scores, and bounding boxes.
    
    Args:
        results: YOLOv8 detection results object
        original_image (Image.Image): Original PIL image for annotation
        conf_threshold (float): Confidence threshold used for filtering
        
    Returns:
        Tuple[Image.Image, pd.DataFrame]: Annotated image and structured detection data
    """
    try:
        # Extract detection data
        detection_list = []
        
        # Check if any detections were found
        if results.boxes is not None and len(results.boxes) > 0:
            # Get class names from the model
            class_names = results.names
            
            # Extract boxes, classes, and confidence scores
            boxes = results.boxes.xyxy.cpu().numpy()  # x1, y1, x2, y2 format
            classes = results.boxes.cls.cpu().numpy()
            confidences = results.boxes.conf.cpu().numpy()
            
            # Process each detection (already filtered by YOLOv8 based on conf_threshold)
            for i in range(len(boxes)):
                class_id = int(classes[i])
                class_name = class_names[class_id]
                confidence = float(confidences[i])
                x1, y1, x2, y2 = boxes[i]
                
                # Create detection record with proper rounding
                detection_record = {
                    'class': class_name,
                    'confidence': round(confidence, 3),  # Round to 3 decimal places
                    'x1': round(float(x1), 1),          # Round to 1 decimal place
                    'y1': round(float(y1), 1),
                    'x2': round(float(x2), 1),
                    'y2': round(float(y2), 1)
                }
                
                detection_list.append(detection_record)
                
            logger.info("Parsed %d detections above confidence threshold %.2f", len(detection_list), conf_threshold)
        else:
            logger.info("No objects detected above confidence threshold %.2f", conf_threshold)
        
        # Create DataFrame from detection list with proper columns
        if detection_list:
            detection_df = pd.DataFrame(detection_list)
        else:
            # Create empty DataFrame with correct columns
            detection_df = pd.DataFrame(columns=['class', 'confidence', 'x1', 'y1', 'x2', 'y2'])
        
        # Generate annotated image using YOLOv8's built-in plotting
        annotated_image = generate_annotated_image(results, original_image)
        
        return annotated_image, detection_df
        
    except Exception as e:
        logger.error("Error parsing detection results: %s", str(e))
        # Return original image and empty dataframe on error
        empty_df = pd.DataFrame(columns=['class', 'confidence', 'x1', 'y1', 'x2', 'y2'])
        return original_image, empty_df


def generate_annotated_image(results, original_image: Image.Image) -> Image.Image:
    """
    Generate annotated image with bounding boxes and labels using YOLOv8's plot method.
    
    Args:
        results: YOLOv8 detection results object
        original_image (Image.Image): Original PIL image
        
    Returns:
        Image.Image: Annotated PIL image with bounding boxes and labels in RGB format
    """
    try:
        # Use YOLOv8's built-in plot method to generate annotations
        # This automatically adds bounding boxes, class labels, and confidence scores
        annotated_array = results.plot(
            conf=True,  # Show confidence scores
            labels=True,  # Show class labels
            boxes=True,  # Show bounding boxes
            line_width=2,  # Line width for bounding boxes
            font_size=12  # Font size for labels
        )
        
        # CRITICAL: YOLOv8's plot() method ALWAYS returns BGR format, but Gradio expects RGB
        # Force BGR to RGB conversion regardless of array shape
        #logger.info("Converting BGR to RGB for proper color display")
        #annotated_rgb = cv2.cvtColor(annotated_array, cv2.COLOR_BGR2RGB)
        
        # Ensure the array is in the correct data type
        annotated_array = annotated_array.astype(np.uint8)
        
        # Convert NumPy array back to PIL Image
        annotated_image = Image.fromarray(annotated_array)
        
        # Verify the conversion worked
        logger.info("Generated annotated image successfully with dimensions: %s, mode: %s", 
                   annotated_image.size, annotated_image.mode)
        return annotated_image
        
    except Exception as e:
        logger.error("Error generating annotated image: %s", str(e))
        # Return original image on error to maintain aspect ratio
        return original_image


def create_csv_download(detection_data: pd.DataFrame, conf_threshold: float = 0.25) -> str:
    """
    Create a CSV file from detection results for download.
    
    Args:
        detection_data (pd.DataFrame): Detection results dataframe
        conf_threshold (float): Confidence threshold used for filtering
        
    Returns:
        str: Path to the created CSV file
    """
    try:
        # Create a temporary CSV file
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        csv_filename = f"detection_results_{timestamp}.csv"
        
        # Use a temporary directory
        temp_dir = tempfile.gettempdir()
        csv_path = os.path.join(temp_dir, csv_filename)
        
        # Save DataFrame to CSV with additional metadata
        if not detection_data.empty:
            # Add metadata to the CSV
            with open(csv_path, 'w', newline='', encoding='utf-8') as f:
                f.write(f"# YOLOv8 Object Detection Results\n")
                f.write(f"# Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write(f"# Confidence threshold: {conf_threshold:.2f} ({conf_threshold*100:.0f}%)\n")
                f.write(f"# Total detections: {len(detection_data)}\n")
                f.write("# Columns: class, confidence, x1, y1, x2, y2\n")
                f.write("# Coordinates are in pixels (x1,y1 = top-left, x2,y2 = bottom-right)\n")
                f.write("#\n")
            
            # Append the actual data
            detection_data.to_csv(csv_path, mode='a', index=False)
        else:
            # Create empty CSV with headers
            detection_data.to_csv(csv_path, index=False)
        
        logger.info("CSV file created successfully: %s", csv_path)
        return csv_path
        
    except Exception as e:
        logger.error("Error creating CSV file: %s", str(e))
        return None


def create_gradio_interface():
    """
    Create Gradio Interface with image upload, confidence slider, and triple output.
    
    Returns:
        gr.Interface: Configured Gradio interface
    """
    # Create the Gradio interface
    demo = gr.Interface(
        fn=detect_objects,
        inputs=[
            gr.Image(
                type="pil",
                label="Upload Image for Object Detection",
                sources=["upload", "clipboard"],
                height=400
            ),
            gr.Slider(
                minimum=0.01,
                maximum=1.0,
                value=0.25,
                step=0.01,
                label="Confidence Threshold",
                info="Only show detections above this confidence level (0.01 = 1%, 1.0 = 100%)"
            )
        ],
        outputs=[
            gr.Image(
                type="pil",
                label="Annotated Image with Detections",
                height=400,
                show_label=True
            ),
            gr.Dataframe(
                label="Detection Results",
                headers=["Class", "Confidence", "X1", "Y1", "X2", "Y2"],
                datatype=["str", "number", "number", "number", "number", "number"],
                col_count=(6, "fixed"),
                row_count=(10, "dynamic"),
                interactive=False
            ),
            gr.File(
                label="Download Results as CSV",
                visible=True
            )
        ],
        title="πŸš— Traffic Bird's Eye View Object Detection",
        description="""
        **Upload an aerial/bird's eye view image to detect traffic objects!**
        
        This application uses a specialized YOLOv8 model trained for traffic detection from aerial perspectives.
        Perfect for analyzing drone footage, satellite images, or overhead traffic cameras.
        
        **Supported formats:** JPG, PNG, JPEG
        
        **Features:** 
        - πŸš— Specialized traffic detection model
        - 🎚️ Adjustable confidence threshold slider
        - πŸ“₯ Download detection results as CSV
        - πŸ“Š Real-time filtering based on confidence scores
        - πŸ–ΌοΈ Example images to try out
        """,
        article="""
        ### How it works:
        1. **Upload** an aerial/bird's eye view image or **select from examples** below
        2. **Adjust** the confidence threshold slider to filter detections (default: 0.25 = 25%)
        3. **View** the annotated image with bounding boxes and labels for detected traffic objects
        4. **Analyze** the detection data in the table with confidence scores and coordinates
        5. **Download** the results as a CSV file for further analysis
        
        **Best Results:** This model works best with:
        - 🚁 Drone footage of roads and traffic
        - πŸ›°οΈ Aerial photography of urban areas
        - πŸ“Ή Overhead traffic camera feeds
        - πŸ—ΊοΈ Bird's eye view street scenes
        
        **Confidence Threshold Guide:**
        - **0.01-0.20**: Very permissive - shows many detections, including uncertain ones
        - **0.25-0.50**: Balanced - good mix of accuracy and detection count (recommended)
        - **0.50-0.80**: Conservative - only high-confidence detections
        - **0.80-1.00**: Very strict - only extremely confident detections
        
        Try the example images below to see the model in action!
        """,
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1200px !important;
        }
        .output-image {
            height: 400px !important;
        }
        .slider-container {
            margin: 10px 0;
        }
        """,
        examples=[
            ["examples/13sbt-aerial-shot-of-white-convertible-car-riding-throug-F5ZX2CK-12.jpg", 0.25],
            ["examples/7sbt-cars-on-the-road-aerial-view-QLX4X43-1481.jpg", 0.25],
            ["examples/13sbt-car-traffic-yellow-autumn-forest-nature-road-lands-SFXKS2M-86.jpg", 0.25],
            ["examples/7sbt-cars-ride-on-the-road-slow-motion-kyiv-ukraine-aer-W6BZ8YJ-5520.jpg", 0.25],
            ["examples/13sbt-DJI_0123-3.jpg", 0.25],
            ["examples/2022teknofest-DJI_0309-86.jpg", 0.25]
        ],
        cache_examples=False,
        flagging_mode="never"
    )
    
    return demo


if __name__ == "__main__":
    # Initialize model on startup
    if not initialize_model():
        logger.error("Failed to initialize YOLOv8 model. Application cannot start.")
        sys.exit(1)
    
    logger.info("YOLOv8 model initialized successfully")
    
    # Create and launch Gradio interface
    try:
        demo = create_gradio_interface()
        logger.info("Gradio interface created successfully")
        
        # Launch the application
        demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=False,
            debug=False,
            show_error=True,
            quiet=False
        )
        
    except Exception as e:
        logger.error("Error launching Gradio interface: %s", str(e))
        sys.exit(1)