There are several problems with your solution - one problem with your math and lots of real world problems that will seriously impact the accuracy of your calculation.
The problem with your formula is that you didn't consider the gaps between pixels - something that is 10 pixels wide in the image actually covers 10 pixels + 9 gaps on the sensor - by ignoring the gaps your calculation will always return a smaller size than the object true size by a constant factor.
As for the real world problems - the first is that this will only work if the object you are measuring is exactly parallel to the camera sensor (or you'll have perspective distortion).
The second is that focal lengths are not accurate, the number in the spec is rounded to the nearest common focal length and even that only when the lens is focused to infinity (focal length changes with focus).
And that's even before we consider distortion caused by the lens and other imperfections of real world optical devices.
Most of the problems can be solved by taking a test shot of an object with a known size