With a given reference its possible. Either calibrate your camera to that reference and dont move it afterwards or have a known scale on each image. That way you can tell what distance equals a pixel. Now you just have to count the pixels and can convert that to your distance.
And yes, you can do it automatically. If the camera is calibrated to the reference, just count the pixels and convert them. If you have a scale on each image, detect that scale, count the pixels and (since you know the real dimensions of the scale) use that to calculate the distance.