Previous studies have shown that perceptions of neighborhood safety are associated with various mental health outcomes. However, scant attention has been paid to the mediating pathways by which perception of neighborhood safety affects mental health. In addition, most previous studies have evaluated perception of neighborhood safety with questionnaires or field audits, both of which are labor-intensive and time-consuming. This study is the first attempt to measure perception of neighborhood safety using street view data and a machine learning approach. Four potential mediating pathways linking perception of neighborhood safety to mental health were explored for 1029 participants from 35 neighborhoods of Guangzhou, China. The results of multilevel regression models confirm that perception of neighborhood safety is positively associated with mental health. More importantly, physical activity, social cohesion, stress and life satisfaction mediate this relationship. The results of a moderation analysis suggest that the beneficial effects of physical activity and social cohesion on mental health are strengthened by a perception of neighborhood safety. Our findings suggest the need to increase residents’ perception of neighborhood safety to maintain mental health in urban areas of China.