'Using python to calculate 3d points in a plane from a 2D image, having some known locations on the 2D image (homography?)

I'm needing to solve a problem where I have a plane in known 3D space (a court), and I know the coordinates of its corners (and other line intersections). I then have a 2D image of the court that I can digitise to find the pixel coordinates.

I understand that I can relate the two via homography (and have successfully done this in MATLAB), and calculate new 3D points based on an (x,y) location in the 2D image. The 3D z-coordinate is always 0.

My question is how can I perform this in Python?

court_coordinates

array([[-3.05 , -6.705,  0.   ],
       [ 3.05 , -6.705,  0.   ],
       [-3.05 ,  0.   ,  0.   ],
       [ 3.05 ,  0.   ,  0.   ],
       [-3.05 ,  6.705,  0.   ],
       [ 3.05 ,  6.705,  0.   ]], dtype=float32)

pixel_coordinates

array([[ 257.4123305 ,  694.90208136],
       [1016.79422895,  694.90208136],
       [ 338.1439609 ,  505.68732261],
       [ 936.06259855,  510.73304951],
       [ 393.6469568 ,  397.20419426],
       [ 885.60532955,  402.24992116]])

New 2D point: [(635.8418479974771, 689.8563544623148)]

This should give a 3D coordinate of (0,-6.705,0)

So far I have tried using cv2.findHomography, inputting my two sets of coordinates. Then I have used the inverse of this matrix, multiplied with the new pixel 2D coordinates, however this doesn't return a realistic 3D coordinate.

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source