How does an MRI work?
The simplest way to detect where a spin in a sample is is to place this in a magnetic field that changes in direct proportion to depth. Then the frequency at which spins respond to the r.f. radiation can be interpreted as a depth. Clearly it is going to be far more complex to get 3D images but in essence is the same; the detected signal has to be encoded with a position.