A derailment detection algorithm for railway freight cars based on micro inertial measurement units was designed to address the complex issue of the disassembly and assembly of derailment braking devices. Firstly, a horizontal attitude measurement model for freight cars was established, and attitude measurement algorithms based on gyroscopes and accelerometers were introduced. Subsequently, a high-precision attitude measurement algorithm based on variational Bayesian Kalman filtering was proposed, which used acceleration information as the observation data to correct attitude errors. In order to improve the accuracy of derailment detection, a dual-model instantaneous attitude difference measurement technique was further proposed. In order to verify the effectiveness of the algorithm, offline data from simulation experiments and in-vehicle experiments were used to validate the proposed algorithm. The results showed that the proposed algorithm can effectively improve the measurement accuracy of horizontal attitude changes, reducing the error by 89% compared to pure inertial attitude calculation, laying a technical foundation for improving the accuracy of derailment detection.