Railway safety is a critical concern due to the increasing number of accidents caused by foreign object intrusion on tracks. Traditional detection methods lack efficiency and fail in complex environments. This paper proposes an improved obstacle detection algorithm based on YOLOv8, a state-of-the-art deep learning model for real-time object detection. Compared to YOLOv5s, YOLOv8 introduces an anchor-free detection mechanism, enhanced backbone architecture using C2f modules, and improved feature fusion techniques. These enhancements significantly improve detection of accuracy, speed, and robustness. The proposed system adopts a two-stage approach, where a lightweight classification model first identifies the presence of foreign objects, followed by YOLOv8 for precise detection and localization. Experimental results demonstrate superior performance in terms of precision, recall, and mean Average Precision, making it highly suitable for real-time railway safety applications.