The ranking method is a key element of content-based image retrieval (CBIR) system, which can affect the final retrieval performance. In the literature, previous ranking methods based on either distance or probability do not explicitly relate to precision and recall, which are normally used to evaluate the performance of CBIR systems. In this paper, a novel ranking method based on relative density is proposed to improve the probability based approach by ranking images in the class. The proposed method can achieve optimal precision and recall. The experiments conducted on a large photographic collection show significant improvements of retrieval performance.