Traditional image segmentation algorithms usually can’t obtain expected effects when facing with complex images such as container code images with complex backgrounds and bad illuminations. This paper introduces the definition of valid gradient and proposes a novel image segmentation algorithm based on it to solve above problem. Through statistical analyzing of the valid gradient information of the edges between the target and the background, some thresholds can be obtained directly and used to segment the images. The experiment results show that the algorithm can get better performance evaluation. Finally, the algorithm has good practicability and can be used directly in different image segmentation fields.