Abstract:Defecation frequency serves as a crucial indicator for assessing pig health and environmental hygiene. However, existing methods struggle to accurately identify and quantify individual defecation behaviors in multi?pig housing environments and long?duration scenarios. To address these challenges, a spatiotemporal attention?based inverse reasoning (SAIR) framework for automated analysis of pig defecation was proposed. The framework first designed a spatial attention?enhanced YOLO v8 model for detecting pigs, pig hindquarters, and feces. It incorporated an improved BoT?SORT algorithm for pig tracking. Subsequently, an adaptive weighted fusion multi?layer perceptron network was proposed for refined recognition of suspected feces with significant background interference and low resolution. Starting from the feces detection frame, the framework backtracks historical trajectories using K?Means clustering to analyze spatial correlations between pigs and feces. Simultaneously, temporal correlations between feces and pigs were computed by using a temporal attention mechanism. Finally, by integrating the spatial and temporal correlations, the model identified the specific pig involved in defecation. In short video tests, the proposed method achieved classification accuracy, recall, and precision of 97.7%, 97.2%, and 98.1%, respectively. In long video scenarios, the F1?score, recall, and precision reached 88.5%, 90.0%, and 87.1%, respectively. The proposed approach effectively reduced recognition errors caused by multiple fecal discharges in a single defecation event and trajectory misjudgments in long?term sequences, providing reliable support for pig defecation behavior recognition and health assessment.