There are many ways to interpret your question, and even if you only need one, others might be interested in other, so I'll write about a few of them.
Projective transformation of the plane
You ask whether the same results you obtained by measuring the photo could also be obtained from a formula. The answer is yes, if you know the transformation. The class of transformations which describes a perspective deformation of a planar figure is the class of plane projective transformations, which can be represented as $3\times 3$ matrices. That matrix can be computed from the images of four points. So if you know the corners of the ruler in your photo, then you can compute all the rest.
If you don't know the corners, but do know where your camera is in relation to the ruler, then you could express all of this as a sequence of 3d transformations and a final projection, resulting in a similar $3\times 3$ matrix in the end.
Scale along a line
A projective scale is uniquely defined by three points, which I'll call $P_0$, $P_1$ and $P_\infty$. You can interpret the first as origin, the second as unit step, and the third as the point at infinity. That last one you can obtain in your photo by intersecting the images of the parallel edges of the ruler. The point where these intersect is the image of infinity. The other two would likely be 0 cm and 1 cm, or perhaps beginning and end of the ruler. If you have these three fixed, then you can use them to measure distacnes using the cross ratio:
So given three points defining the scale, you can compute the original (non-perspective) position using the above formula. And conversely, given the original position, you can find the corresponding point in the photograph.
Constructing a projective scale
Points at integral positions along a perspectively deformed scale can also be constructed geometrically. Here is an interactive illustration of that construction. The site is in German (so far), so here is an explanation:
$0$, $1$ and $\infty$ fix your scale. Draw two arbitrary lines through $\infty$. Choose an arbitrary point on the lower line (drawn in white) and connect it to $0$ and $1$. You obtain two points on the upper line (drawn in black). Then start by the maximal point you have so far, i.e. $1$, connect to the right black point, intersect with the lower line, connect to the left black point, intersect with the line of the scale, and you obtain $2$. The steps to go from $i$ to $i+1$ are the same for all $i\in\mathbb N$.