import os import cv2 import numpy as np import matplotlib.pyplot as plt from shapely.geometry import Polygon, box as shapely_box import streamlit as st from PIL import Image # Utility functions def extract_class_0_coordinates(filename): class_0_coordinates = [] with open(filename, 'r') as file: for line in file: parts = line.strip().split() if len(parts) == 0: continue if parts[0] == '0': coordinates = [float(x) for x in parts[1:]] class_0_coordinates.extend(coordinates) return class_0_coordinates def parse_yolo_box(box_string): values = list(map(float, box_string.split())) if len(values) < 5: raise ValueError(f"Expected at least 5 values, got {len(values)}") return values[0], values[1], values[2], values[3], values[4] def read_yolo_boxes(file_path): boxes = [] with open(file_path, 'r') as f: for line in f: parts = line.strip().split() class_name = COCO_CLASSES[int(parts[0])] x, y, w, h = map(float, parts[1:5]) boxes.append((class_name, x, y, w, h)) return boxes def yolo_to_pixel_coord(x, y, img_width, img_height): return int(x * img_width), int(y * img_height) def yolo_to_pixel_coords(x_center, y_center, width, height, img_width, img_height): x1 = int((x_center - width / 2) * img_width) y1 = int((y_center - height / 2) * img_height) x2 = int((x_center + width / 2) * img_width) y2 = int((y_center + height / 2) * img_height) return x1, y1, x2, y2 def box_segment_relationship(yolo_box, segment, img_width, img_height, threshold): class_id, x_center, y_center, width, height = yolo_box x1, y1, x2, y2 = yolo_to_pixel_coords(x_center, y_center, width, height, img_width, img_height) pixel_segment = convert_segment_to_pixel(segment, img_width, img_height) segment_polygon = Polygon(zip(pixel_segment[::2], pixel_segment[1::2])) box_polygon = shapely_box(x1, y1, x2, y2) if box_polygon.intersects(segment_polygon): return "intersecting" elif box_polygon.distance(segment_polygon) <= threshold: return "obstructed" else: return "not touching" def convert_segment_to_pixel(segment, img_width, img_height): pixel_segment = [] for i in range(0, len(segment), 2): x, y = yolo_to_pixel_coord(segment[i], segment[i+1], img_width, img_height) pixel_segment.extend([x, y]) return pixel_segment def plot_boxes_and_segment(image, yolo_boxes, segment, img_width, img_height, threshold): fig, ax = plt.subplots(figsize=(12, 8)) ax.imshow(image) pixel_segment = convert_segment_to_pixel(segment, img_width, img_height) ax.plot(pixel_segment[::2] + [pixel_segment[0]], pixel_segment[1::2] + [pixel_segment[1]], 'g-', linewidth=2, label='Rail Zone') colors = {'intersecting': 'r', 'obstructed': 'y', 'not touching': 'b'} labels = {'intersecting': 'Intersecting Box', 'obstructed': 'Obstructed Box', 'not touching': 'Non-interacting Box'} for yolo_box in yolo_boxes: class_id, x_center, y_center, width, height = yolo_box x1, y1, x2, y2 = yolo_to_pixel_coords(x_center, y_center, width, height, img_width, img_height) relationship = box_segment_relationship(yolo_box, segment, img_width, img_height, threshold) color = colors[relationship] label = labels[relationship] ax.add_patch(plt.Rectangle((x1, y1), x2-x1, y2-y1, fill=False, edgecolor=color, linewidth=2, label=label)) ax.legend() ax.axis('off') plt.tight_layout() return fig # COCO classes COCO_CLASSES = [ 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus', 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush' ] # Detection functions def detect_rail(image): # Open the image using PIL pil_image = Image.open(image) # Convert PIL image to numpy array image = np.array(pil_image) # Check if the image is RGB (3 channels) if len(image.shape) == 3 and image.shape[2] == 3: # Convert RGB to BGR (OpenCV format) image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) else: # If not RGB, just use the image as is (assuming it's already in a format OpenCV can handle) image_bgr = image temp_image_path = "temp_image_rail.jpg" cv2.imwrite(temp_image_path, image_bgr) os.system(f"python segment/predict.py --source {temp_image_path} --img 640 --device cpu --weights models/segment/best-2.pt --name yolov9_c_640_detect --exist-ok --save-txt") label_path = 'runs/predict-seg/yolov9_c_640_detect/labels/temp_image_rail.txt' segment = extract_class_0_coordinates(label_path) fig, ax = plt.subplots(figsize=(12, 8)) ax.imshow(image) # Use the original image for display img_height, img_width = image.shape[:2] pixel_segment = convert_segment_to_pixel(segment, img_width, img_height) ax.plot(pixel_segment[::2] + [pixel_segment[0]], pixel_segment[1::2] + [pixel_segment[1]], 'g-', linewidth=2, label='Rail Zone') ax.legend() ax.axis('off') plt.tight_layout() os.remove(temp_image_path) os.remove(label_path) return fig, segment def detect_objects(image, rail_segment): # Open the image using PIL pil_image = Image.open(image) # Convert PIL image to numpy array image = np.array(pil_image) # Check if the image is RGB (3 channels) if len(image.shape) == 3 and image.shape[2] == 3: # Convert RGB to BGR (OpenCV format) image_bgr = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) else: # If not RGB, just use the image as is (assuming it's already in a format OpenCV can handle) image_bgr = image img_height, img_width = image.shape[:2] temp_image_path = "temp_image_objects.jpg" cv2.imwrite(temp_image_path, image_bgr) os.system(f"python detect.py --source {temp_image_path} --img 640 --device cpu --weights models/detect/yolov9-s-converted.pt --name yolov9_c_640_detect --exist-ok --save-txt") label_path = 'runs/detect/yolov9_c_640_detect/labels/temp_image_objects.txt' yolo_boxes = read_yolo_boxes(label_path) threshold = 10 # Set threshold (in pixels) fig = plot_boxes_and_segment(image, yolo_boxes, rail_segment, img_width, img_height, threshold) results = [] for class_name, x, y, w, h in yolo_boxes: result = box_segment_relationship((0, x, y, w, h), rail_segment, img_width, img_height, threshold) results.append(f"{class_name} at ({x:.2f}, {y:.2f}) is {result} the segment.") os.remove(temp_image_path) os.remove(label_path) return fig, "\n".join(results) # Streamlit app def main(): st.title("Two-Step Train Obstruction Detection") st.write("Step 1: Upload an image to detect the rail. Step 2: Upload an image with objects to detect obstructions.") # Step 1: Rail Detection st.header("Step 1: Rail Detection") rail_image = st.file_uploader("Upload image for rail detection", type=["jpg", "jpeg", "png"]) if rail_image is not None: rail_fig, rail_segment = detect_rail(rail_image) st.pyplot(rail_fig) st.success("Rail detection completed!") # Step 2: Object Detection st.header("Step 2: Object Detection") object_image = st.file_uploader("Upload image for object detection", type=["jpg", "jpeg", "png"]) if object_image is not None: object_fig, object_results = detect_objects(object_image, rail_segment) st.pyplot(object_fig) st.text_area("Analysis Results", object_results, height=200) st.success("Object detection and analysis completed!") if __name__ == "__main__": main()