Displacement measurement technology based on image recognition algorithms represents a novel high-performance technique. In such measurements, when there are stains contaminating the measuring light path, it causes recognition errors from the linear array image sensor on the grating, resulting in inaccurate measurement results. Therefore, this report proposes stain-detection and anti-stain algorithms based on image recognition. The principle of image-type displacement measurement technology is described, and the influence of stains on the displacement measurements is analyzed according to four criteria in order to judge whether there are stains present. Then, an anti-stain algorithm based on the data exchange of dual-image sensors is proposed. Finally, experimental verifications are carried out. The experimental results show that the proposed algorithm effectively identifies the errors in the displacement measurements, when the experimental device is contaminated, the developed algorithms can accurately self-correct for the stain's interference. The results presented herein provide a theoretical basis for developing highly-reliable displacement measurement devices.