The Shack-Hartmann wavefront sensor (SHWFS) is an optical detection device based on the measurements of wavefront slopes. It is widely used in an adaptive optics system due to its simple structure and strong environment adaptability. The measuring accuracy of the SHWFS depends mainly on the accuracy of the spot image centroid in each sub-aperture. There are many centroid algorithms including the center of gravity algorithm, Gauss fitting algorithm, and correlation algorithm. As to the simplicity, robustness, high accuracy and stability, the center of gravity algorithm is more widely used. However, the accuracy of gravity algorithm is sensitive to the noise including discretization, aliasing, photon noise, readout noise, stray light, and direct current bias. To improve the accuracy of centroid, the output signals of SHWFS must be pre-processed to suppress the noise effect by using the method of thresholding in general. Many threshold methods have been presented to reduce the error of centroid and there theoretically exists an optimum threshold which causes the minimum error of centroid based on the characteristics of SHWFS and noise. However, it is difficult to separate the signals from the noises, and the optimum threshold cannot be estimated accurately in real time in the SHWFS systems. In this paper aiming at noises in SHWFS, which vary with time and space rapidly, a method based on the noise weighted function of the mean value of pixels and the local gradient direction of image signals in the moving windows is presented according to the characteristics of the Gaussian spot and noise distributions. Moreover, the theory and parameters determination of the method are analyzed. The method utilizes the probability that the pixels in the moving windows belong to the noise, and the probability is inversely proportional to the mean value of pixels and the local gradient direction of image signals, and so the monotonically reducing probability function of pixels is constructed. Finally, the standard deviation and mean value of noise can be obtained, and the estimation value of optimum threshold is equal to the mean value of noise plus three times the standard deviation of noise. To investigate the effects of the optimum threshold estimation with the different spot sizes, spot strengths and noise levels, the proposed algorithm is compared with traditional methods. The simulation and experimental results show that the proposed method could achieve higher accuracy, and the error between the threshold obtained by the method presented in this paper and theoretical optimum threshold is less than 10%, which is less than those from the traditional methods.