This work investigates the potential application of CMOS pixel sensors, designed for particle tracking, for the detection of X rays. We explain how the image definition can be improved exploiting the single photon counting technique. An experimental system, based on an X ray source, is developed to measure the single point resolution of photons. Thanks to a full GEANT4 simulation of the device, the evaluation uncertainty is predicted to be 2 µm. We apply our method to the direct detection of low energy (< 10 keV) X rays by a CMOS pixel to measure a spatial resolution of 52 lp/mm. For higher energies, an hybrid device, coupling a CSi(Tl) highly segmented crystal with a CMOS sensor, is used. The spatial resolution reaches in this case 15 lp/mm. A detailed simulation study demonstrated that this limited performance is related to the characteristics of the light emitted by the crystal.