find homography given calibration matrix, pixel coordinates and 3d coordinates in matlab

To find the homography given calibration matrix, pixel coordinates and 3D coordinates in MATLAB, you can use the fitgeotrans function. Here's an example code snippet:

main.m
% Given calibration matrix
K = [fx 0 cx; 0 fy cy; 0 0 1];

% Given pixel coordinates (2D)
u = [u1 u2 u3 ...]';
v = [v1 v2 v3 ...]';

% Given 3D coordinates (homogeneous)
X = [X1 X2 X3 ...;
     Y1 Y2 Y3 ...;
     Z1 Z2 Z3 ...;
     1  1  1  ...];

% Compute normalized points
x = (K \ [u; v; ones(size(u))])';
X = X(1:3,:)';
x_norm = bsxfun(@rdivide, x, x(:,3));

% Compute homography
tform = fitgeotrans(X, x_norm, 'projective');

% Extract homography
H = tform.T';
467 chars
24 lines

In this code, fx, fy, cx, and cy are the intrinsic parameters of the camera, and u1, u2, u3, ... , v1, v2, v3, ... are the corresponding pixel coordinates. X1, X2, X3, ... , Y1, Y2, Y3, ... , Z1, Z2, Z3, ... are the corresponding 3D coordinates. The fitgeotrans function uses the 3D coordinates and their corresponding normalized pixel coordinates to compute the homography, which is returned as H.

gistlibby LogSnag