Functional near-infrared spectroscopy (fNIRS), as a new optical functional neuroimaging method, has been widely used in neuroscience research. In some research¯elds with NIRS, heartrate (HR) (or heartbeat) is needed as useful information to evaluate its in°uence, or to know the state of subject, or to remove its artifact. If HR (or heartbeat) can be detected with high accuracy from the optical intensity, this will undoubtedly bene¯t a lot to many NIRS studies. Previous studies have used the moving time window method or mathematical morphology method (MMM) to detect heartbeats in the optical intensity. However, there are some disadvantages in these methods. In this study, we proposed a method combining the periodic information of heartbeats and the operator of mathematical morphology to automatically detect heartbeats in the optical intensity. First the optical intensity is smoothed using a moving average¯lter. Then, the opening operator of mathematical morphology extracts peaks in the smoothed optical intensity. Finally, one peak is identi¯ed as a heartbeat peak if this peak is the maximum in a prede¯ned point range. Through validation on experimental data, our method can overcome the disadvantages of previous methods, and detect heartbeats in the optical signal of fNIRS with nearly 100% accuracy.