<p>I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?</p>

<p>I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.</p>

<p>This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information. </p>

[{'answer_id': 76282, 'author': 'tzot', 'author_id': 6899, 'author_profile': 'https://Stackoverflow.com/users/6899', 'pm_score': 2, 'selected': False, 'text': "<p>Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :</p>\n\n<p>Find two points with max inter-distance: these most probably define a diagonal (exception: special cases where the rectangle is almost paralell to the YZ plane, left for the student). Call them A, C. Calculate the BAD, BCD angles. These, compared to right angles, give you orientation in 3d space. To find out about z distance, you need to correlate the projected sides to the known sides, and then, based on the 3d projection method (is it 1/z?) you're on the right track to know distances.</p>\n"}, {'answer_id': 76289, 'author': 'nlucaroni', 'author_id': 157, 'author_profile': 'https://Stackoverflow.com/users/157', 'pm_score': 1, 'selected': False, 'text': '<p>I\'ll get my linear Algebra book out when I get home if nobody answered. But @ D G, not all matrices are invertible. <a href="http://mathworld.wolfram.com/SingularMatrix.html" rel="nofollow noreferrer">Singular matrices aren\'t invertible</a> (when determinant = 0). This will actually happen all the time, since a projection matrix <em>must</em> have eigenvalues of 0 and 1, and be square (since it is idempotent, so p^2 = p).</p>\n\n<p>An easy example is, [[0 1][0 1]] since the determinant = 0, and that is a projection on the line x = y!</p>\n'}, {'answer_id': 76305, 'author': 'Rob Dickerson', 'author_id': 7530, 'author_profile': 'https://Stackoverflow.com/users/7530', 'pm_score': 1, 'selected': False, 'text': '<p>The projection you have onto the 2D surface has infinitely many 3D rectangles that will project to the same 2D shape.</p>\n\n<p>Think about it this way: you have four 3D points that make up the 3D rectangle. Call them (x0,y0,z0), (x1,y1,z1), (x2,y2,z2) and (x3,y3,z3). When you project these points onto the x-y plane, you drop the z coordinates: (x0,y0), (x1,y1), (x2,y2), (x3,y3).</p>\n\n<p>Now, you want to project back into 3D space, you need to reverse-engineer what z0,..,z3 were. But any set of z coordinates that a) keep the same x-y distance between the points, and b) keep the shape a rectangle will work. So, any member of this (infinite) set will do: {(z0+i, z1+i, z2+i, z3+i) | i &lt;- R}.</p>\n\n<p>Edit @Jarrett: Imagine you solved this and ended up with a rectangle in 3D space. Now, imagine sliding that rectangle up and down the z-axis. Those infinite amount of translated rectangles all have the same x-y projection. How do you know you found the "right" one?</p>\n\n<p>Edit #2: Alright, this is from a comment I made on this question -- a more intuitive approach to reasoning about this.</p>\n\n<p>Imagine holding a piece of paper above your desk. Pretend each corner of the paper has a weightless laser pointer attached to it that points down toward the desk. The paper is the 3D object, and the laser pointer dots on the desk are the 2D projection.</p>\n\n<p>Now, how can you tell how high off the desk the paper is by looking at <em>just</em> the laser pointer dots?</p>\n\n<p>You can\'t. Move the paper straight up and down. The laser pointers will still shine on the same spots on the desk regardless of the height of the paper.</p>\n\n<p>Finding the z-coordinates in the reverse-projection is like trying to find the height of the paper based on the laser pointer dots on the desk alone.</p>\n'}, {'answer_id': 76306, 'author': 'Jarrett Meyer', 'author_id': 5834, 'author_profile': 'https://Stackoverflow.com/users/5834', 'pm_score': 2, 'selected': False, 'text': '<p>From the 2-D space there will be 2 valid rectangles that can be built. Without knowing the original matrix projection, you won\'t know which one is correct. It\'s the same as the "box" problem: you see two squares, one inside the other, with the 4 inside vertices connected to the 4 respective outside vertices. Are you looking at a box from the top-down or the bottom-up?</p>\n\n<p>That being said, you are looking for a matrix transform T where...</p>\n\n<p>{{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4, z4}} x T = {{x1, y1}, {x2, y2}, {x3, y3}, {x4, y4}}</p>\n\n<p>(4 x 3) x T = (4 x 2)</p>\n\n<p>So T must be a (3 x 2) matrix. So we\'ve got 6 unknowns.</p>\n\n<p>Now build a system of constraints on T and solve with Simplex. To build the constraints, you know that a line passing through the first two points must be parallel to the line passing to the second two points. You know a line passing through points 1 and 3 must be parallel to the lines passing through points 2 and 4. You know a line passing through 1 and 2 must be orthogonal to a line passing through points 2 and 3. You know that the length of the line from 1 and 2 must equal the length of the line from 3 and 4. You know that the length of the line from 1 and 3 must equal the length of the line from 2 and 4.</p>\n\n<p>To make this even easier, you know about the rectangle, so you know the length of all the sides.</p>\n\n<p>That should give you plenty of constraints to solve this problem.</p>\n\n<p>Of course, to get back, you can find T-inverse.</p>\n\n<p>@Rob: Yes, there are an infinite number of projections, but not an infinite number of projects where the points must satisfy the requirements of a rectangle.</p>\n\n<p>@nlucaroni: Yes, this is only solvable if you have four points in the projection. If the rectangle projects to just 2 points (i.e. the plane of the rectangle is orthogonal to the projection surface), then this cannot be solved.</p>\n\n<p>Hmmm... I should go home and write this little gem. This sounds like fun.</p>\n\n<p>Updates:</p>\n\n<ol>\n<li>There are an infinite number of projections unless you fix one of the points. If you fix on of the points of the original rectangle, then there are two possible original rectangles.</li>\n</ol>\n'}, {'answer_id': 77003, 'author': 'morechilli', 'author_id': 5427, 'author_profile': 'https://Stackoverflow.com/users/5427', 'pm_score': 1, 'selected': False, 'text': "<p>When you project from 3D to 2D you lose information.</p>\n\n<p>In the simple case of a single point the inverse projection would give you an infinite ray through 3d space.</p>\n\n<p>Stereoscopic reconstruction will typically start with two 2d images and project both back to 3D.  Then look for an intersection of the two 3D rays produced.</p>\n\n<p>Projection can take different forms.  Orthogonal or perspective.  I'm guessing that you are assuming orthogonal projection?</p>\n\n<p>In your case assuming you had the original matrix you would have 4 rays in 3D space.  You would then be able to constrain the problem by your 3d rectangle dimensions and attempt to solve.  </p>\n\n<p>The solution will not be unique as a rotation around either axis that is parallel to the 2d projection plane will be ambiguous in direction.  In other words if the 2d image is perpendicular to the z axis then rotating the 3d rectangle clockwise or anti clockwise around the x axis would produce the same image.  Likewise for the y axis.</p>\n\n<p>In the case where the rectangle plane is parallel to the z axis you have even more solutions.</p>\n\n<p>As you don't have the original projection matrix further ambiguity is introduced by an arbitary scaling factor that exists in any projection.  You cannot distinguish between a scaling in the projection and a translation in 3d in the direction of the z axis.  This is not a problem if you are only interested in the relative positions of the 4 points in 3d space when related to each other and not to the plane of the 2d projection.</p>\n\n<p>In a perspective projection things get harder...</p>\n"}, {'answer_id': 77188, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>If you know the shape is a rectangle in a plane, you can greatly further constrain the problem. You certainly cannot figure out "which" plane, so you can choose that it is lying on the plane where z=0 and one of the corners is at x=y=0, and the edges are parallel to the x/y axis.</p>\n\n<p>The points in 3d are therefore {0,0,0},{w,0,0},{w,h,0},and {0,h,0}. I\'m pretty certain the absolute size will not be found, so only the ratio w/h is releavant, so this is one unknown.</p>\n\n<p>Relative to this plane the camera must be at some point cx,cy,cz in space, must be pointing in a direction nx,ny,nz (a vector of length one so one of these is redundant), and have a focal_length/image_width factor of w. These numbers turn into a 3x3 projection matrix.</p>\n\n<p>That gives a total of 7 unknowns: w/h, cx, cy, cz, nx, ny, and w.</p>\n\n<p>You have a total of 8 knowns: the 4 x+y pairs.</p>\n\n<p>So this can be solved.</p>\n\n<p>Next step is to use Matlab or Mathmatica.</p>\n'}, {'answer_id': 78057, 'author': 'user14208', 'author_id': 14208, 'author_profile': 'https://Stackoverflow.com/users/14208', 'pm_score': 3, 'selected': False, 'text': "<p>For my OpenGL engine, the following snip will convert mouse/screen coordinates into 3D world coordinates.  Read the commments for an actual description of what is going on.</p>\n<pre>\n/*   FUNCTION:        YCamera :: CalculateWorldCoordinates\n     ARGUMENTS:       x         mouse x coordinate\n                      y         mouse y coordinate\n                      vec       where to store coordinates\n     RETURN:          n/a\n     DESCRIPTION:     Convert mouse coordinates into world coordinates\n*/\n</pre>\n<pre><code>void YCamera :: CalculateWorldCoordinates(float x, float y, YVector3 *vec)\n{\n    //  START\n    GLint viewport[4];\n    GLdouble mvmatrix[16], projmatrix[16];\n    \n    GLint real_y;\n    GLdouble mx, my, mz;\n\n    glGetIntegerv(GL_VIEWPORT, viewport);\n    glGetDoublev(GL_MODELVIEW_MATRIX, mvmatrix);\n    glGetDoublev(GL_PROJECTION_MATRIX, projmatrix);\n\n    real_y = viewport[3] - (GLint) y - 1;   // viewport[3] is height of window in pixels\n    gluUnProject((GLdouble) x, (GLdouble) real_y, 1.0, mvmatrix, projmatrix, viewport, &amp;mx, &amp;my, &amp;mz);\n\n    /*  'mouse' is the point where mouse projection reaches FAR_PLANE.\n        World coordinates is intersection of line(camera-&gt;mouse) with plane(z=0) (see LaMothe 306)\n        \n        Equation of line in 3D:\n            (x-x0)/a = (y-y0)/b = (z-z0)/c      \n\n        Intersection of line with plane:\n            z = 0\n            x-x0 = a(z-z0)/c  &lt;=&gt; x = x0+a(0-z0)/c  &lt;=&gt; x = x0 -a*z0/c\n            y = y0 - b*z0/c\n            \n    */\n    double lx = fPosition.x - mx;\n    double ly = fPosition.y - my;\n    double lz = fPosition.z - mz;\n    double sum = lx*lx + ly*ly + lz*lz;\n    double normal = sqrt(sum);\n    double z0_c = fPosition.z / (lz/normal);\n    \n    vec-&gt;x = (float) (fPosition.x - (lx/normal)*z0_c);\n    vec-&gt;y = (float) (fPosition.y - (ly/normal)*z0_c);\n    vec-&gt;z = 0.0f;\n}\n</code></pre>\n"}, {'answer_id': 93779, 'author': 'Nils Pipenbrinck', 'author_id': 15955, 'author_profile': 'https://Stackoverflow.com/users/15955', 'pm_score': 2, 'selected': False, 'text': '<p>To follow up on Rons approach: You can find your z-values if you know how you\'ve rotated your rectangle.</p>\n\n<p>The trick is to find the projective matrix that did the projection. Fortunately this is possible and even cheap to do. The relevant math can be found in the paper "Projective Mappings for Image Warping" by Paul Heckbert. </p>\n\n<p><a href="http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf" rel="nofollow noreferrer">http://pages.cs.wisc.edu/~dyer/cs766/readings/heckbert-proj.pdf</a></p>\n\n<p>This way you can recover the homogenous part of each vertex back that was lost during projection. </p>\n\n<p>Now you\'re still left with four lines instead of points (as Ron explained). Since you know the size of your original rectangle however nothing is lost. You can now plug the data from Ron\'s method and from the 2D approach into a linear equation solver and solve for z. You get the exact z-values of each vertex that way. </p>\n\n<p>Note: This just works because: </p>\n\n<ol>\n<li>The original shape was a rectangle</li>\n<li>You know the exact size of the rectangle in 3D space.</li>\n</ol>\n\n<p>It\'s a special case really.</p>\n\n<p>Hope it helps,\n  Nils</p>\n'}, {'answer_id': 3554754, 'author': 'Julien-L', 'author_id': 143504, 'author_profile': 'https://Stackoverflow.com/users/143504', 'pm_score': 3, 'selected': False, 'text': '<p><em>D. DeMenthon</em> devised an algorithm to compute the <em>pose</em> of an object (its position and orientation in space) from feature points in a 2D image when knowing the model of the object -- <strong>this is your exact problem</strong>:</p>\n\n<blockquote>\n  <p>We describe a method for finding the pose of an object from a single image. We assume that we can detect and match in the image four or more noncoplanar feature points of the object, and that we know their relative geometry on the object.</p>\n</blockquote>\n\n<p>The algorithm is known as <strong>Posit</strong> and is described in it classical article "Model-Based Object Pose in 25 Lines of Code" (available on <a href="http://www.cfar.umd.edu/~daniel/Site_2/Research.html" rel="noreferrer">its website</a>, section 4).</p>\n\n<p>Direct link to the article: <a href="http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf" rel="noreferrer">http://www.cfar.umd.edu/~daniel/daniel_papersfordownload/Pose25Lines.pdf</a>\nOpenCV implementation: <a href="http://opencv.willowgarage.com/wiki/Posit" rel="noreferrer">http://opencv.willowgarage.com/wiki/Posit</a></p>\n\n<p>The idea is to repeatedly approximating the perspective projection by a <em>scaled orthographic projection</em> until converging to an accurate pose.</p>\n'}, {'answer_id': 13937210, 'author': 'dim_tz', 'author_id': 1435500, 'author_profile': 'https://Stackoverflow.com/users/1435500', 'pm_score': 3, 'selected': False, 'text': '<p>This is the Classic problem for marker based Augmented Reality.</p>\n\n<p>You have a square marker (2D Barcode), and you want to find its Pose (translation &amp; rotation in relation to the camera), after finding the four edges of the marker.\n<a href="http://www.brightsideofnews.com/Data/2009_10_26/Zombies-nVidia-Tegra-Augmented-Reality/Zombies_AR_Marker_675.jpg" rel="noreferrer">Overview-Picture</a></p>\n\n<p>I\'m not aware of the latest contributions to the field, but at least up to a point (2009) RPP was supposed to outperform POSIT that is mentioned above (and is indeed a classic approach for this)\nPlease see the links, they also provide source.</p>\n\n<ul>\n<li><p><a href="http://www.emt.tugraz.at/~vmg/schweighofer" rel="noreferrer">http://www.emt.tugraz.at/~vmg/schweighofer</a></p></li>\n<li><p><a href="http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf" rel="noreferrer">http://www.emt.tugraz.at/publications/EMT_TR/TR-EMT-2005-01.pdf</a></p></li>\n<li><p><a href="http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz" rel="noreferrer">http://www.emt.tugraz.at/system/files/rpp_MATLAB_ref_implementation.tar.gz</a></p></li>\n</ul>\n\n<p>(PS - I know it\'s a bit old topic, but anyway, the post might be helpful to somebody)</p>\n'}, {'answer_id': 33976739, 'author': 'Vegard', 'author_id': 1697183, 'author_profile': 'https://Stackoverflow.com/users/1697183', 'pm_score': 7, 'selected': False, 'text': '<p>Alright, I came here looking for an answer and didn\'t find something simple and straightforward, so I went ahead and did the dumb but effective (and relatively simple) thing: Monte Carlo optimisation.</p>\n\n<p>Very simply put, the algorithm is as follows: Randomly perturb your projection matrix until it projects your known 3D coordinates to your known 2D coordinates.</p>\n\n<p>Here is a still photo from Thomas the Tank Engine:</p>\n\n<p><a href="https://i.stack.imgur.com/YUhsm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YUhsm.png" alt="Thomas the Tank Engine"></a></p>\n\n<p>Let\'s say we use GIMP to find the 2D coordinates of what we think is a square on the ground plane (whether or not it is really a square depends on your judgment of the depth):</p>\n\n<p><a href="https://i.stack.imgur.com/u8nKF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/u8nKF.png" alt="With an outline of the square"></a></p>\n\n<p>I get four points in the 2D image: <code>(318, 247)</code>, <code>(326, 312)</code>, <code>(418, 241)</code>, and <code>(452, 303)</code>.</p>\n\n<p>By convention, we say that these points should correspond to the 3D points: <code>(0, 0, 0)</code>, <code>(0, 0, 1)</code>, <code>(1, 0, 0)</code>, and <code>(1, 0, 1)</code>. In other words, a unit square in the y=0 plane.</p>\n\n<p>Projecting each of these 3D coordinates into 2D is done by multiplying the 4D vector <code>[x, y, z, 1]</code> with a 4x4 projection matrix, then dividing the x and y components by z to actually get the perspective correction. This is more or less what <a href="https://www.opengl.org/sdk/docs/man2/xhtml/gluProject.xml" rel="noreferrer">gluProject()</a> does, except <code>gluProject()</code> also takes the current viewport into account and takes a separate modelview matrix into account (we can just assume the modelview matrix is the identity matrix). It is very handy to look at the <code>gluProject()</code> documentation because I actually want a solution that works for OpenGL, but beware that the documentation is missing the division by z in the formula.</p>\n\n<p>Remember, the algorithm is to start with some projection matrix and randomly perturb it until it gives the projection that we want. So what we\'re going to do is project each of the four 3D points and see how close we get to the 2D points we wanted. If our random perturbations cause the projected 2D points to get closer to the ones we marked above, then we keep that matrix as an improvement over our initial (or previous) guess.</p>\n\n<p>Let\'s define our points:</p>\n\n<pre><code># Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n</code></pre>\n\n<p>We need to start with some matrix, identity matrix seems a natural choice:</p>\n\n<pre><code>mat = [\n    [1, 0, 0, 0],\n    [0, 1, 0, 0],\n    [0, 0, 1, 0],\n    [0, 0, 0, 1],\n]\n</code></pre>\n\n<p>We need to actually implement the projection (which is basically a matrix multiplication):</p>\n\n<pre><code>def project(p, mat):\n    x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n    y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n    w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n    return Point(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n</code></pre>\n\n<p>This is basically what <code>gluProject()</code> does, 720 and 576 are the width and height of the image, respectively (i.e. the viewport), and we subtract from 576 to count for the fact that we counted y coordinates from the top while OpenGL typically counts them from the bottom. You\'ll notice we\'re not calculating z, that\'s because we don\'t really need it here (though it could be handy to ensure it falls within the range that OpenGL uses for the depth buffer).</p>\n\n<p>Now we need a function for evaluating how close we are to the correct solution. The value returned by this function is what we will use to check whether one matrix is better than another. I chose to go by sum of squared distances, i.e.:</p>\n\n<pre><code># The squared distance between two points a and b\ndef norm2(a, b):\n    dx = b.x - a.x\n    dy = b.y - a.y\n    return dx * dx + dy * dy\n\ndef evaluate(mat): \n    c0 = project(r0, mat)\n    c1 = project(r1, mat)\n    c2 = project(r2, mat)\n    c3 = project(r3, mat)\n    return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)\n</code></pre>\n\n<p>To perturb the matrix, we simply pick an element to perturb by a random amount within some range:</p>\n\n<pre><code>def perturb(amount):\n    from copy import deepcopy\n    from random import randrange, uniform\n    mat2 = deepcopy(mat)\n    mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n</code></pre>\n\n<p>(It\'s worth noting that our <code>project()</code> function doesn\'t actually use <code>mat[2]</code> at all, since we don\'t compute z, and since all our y coordinates are 0 the <code>mat[*][1]</code> values are irrelevant as well. We could use this fact and never try to perturb those values, which would give a small speedup, but that is left as an exercise...)</p>\n\n<p>For convenience, let\'s add a function that does the bulk of the approximation by calling <code>perturb()</code> over and over again on what is the best matrix we\'ve found so far:</p>\n\n<pre><code>def approximate(mat, amount, n=100000):\n    est = evaluate(mat)\n\n    for i in xrange(n):\n        mat2 = perturb(mat, amount)\n        est2 = evaluate(mat2)\n        if est2 &lt; est:\n            mat = mat2\n            est = est2\n\n    return mat, est\n</code></pre>\n\n<p>Now all that\'s left to do is to run it...:</p>\n\n<pre><code>for i in xrange(100):\n    mat = approximate(mat, 1)\n    mat = approximate(mat, .1)\n</code></pre>\n\n<p>I find this already gives a pretty accurate answer. After running for a while, the matrix I found was:</p>\n\n<pre><code>[\n    [1.0836000765696232,  0,  0.16272110011060575, -0.44811064935115597],\n    [0.09339193527789781, 1, -0.7990570384334473,   0.539087345090207  ],\n    [0,                   0,  1,                    0                  ],\n    [0.06700844759602216, 0, -0.8333379578853196,   3.875290562060915  ],\n]\n</code></pre>\n\n<p>with an error of around <code>2.6e-5</code>. (Notice how the elements we said were not used in the computation have not actually been changed from our initial matrix; that\'s because changing these entries would not change the result of the evaluation and so the change would never get carried along.)</p>\n\n<p>We can pass the matrix into OpenGL using <code>glLoadMatrix()</code> (but remember to transpose it first, and remember to load your modelview matrix with the identity matrix):</p>\n\n<pre><code>def transpose(m):\n    return [\n        [m[0][0], m[1][0], m[2][0], m[3][0]],\n        [m[0][1], m[1][1], m[2][1], m[3][1]],\n        [m[0][2], m[1][2], m[2][2], m[3][2]],\n        [m[0][3], m[1][3], m[2][3], m[3][3]],\n    ]\n\nglLoadMatrixf(transpose(mat))\n</code></pre>\n\n<p>Now we can for example translate along the z axis to get different positions along the tracks:</p>\n\n<pre><code>glTranslate(0, 0, frame)\nframe = frame + 1\n\nglBegin(GL_QUADS)\nglVertex3f(0, 0, 0)\nglVertex3f(0, 0, 1)\nglVertex3f(1, 0, 1)\nglVertex3f(1, 0, 0)\nglEnd()\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/dfeEx.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/dfeEx.gif" alt="With 3D translation"></a></p>\n\n<p>For sure this is not very elegant from a mathematical point of view; you don\'t get a closed form equation that you can just plug your numbers into and get a direct (and accurate) answer. HOWEVER, it does allow you to add additional constraints without having to worry about complicating your equations; for example if we wanted to incorporate height as well, we could use that corner of the house and say (in our evaluation function) that the distance from the ground to the roof should be so-and-so, and run the algorithm again. So yes, it\'s a brute force of sorts, but works, and works well.</p>\n\n<p><a href="https://i.stack.imgur.com/smdR8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/smdR8.png" alt="Choo choo!"></a></p>\n'}, {'answer_id': 39877333, 'author': 'BBSysDyn', 'author_id': 423805, 'author_profile': 'https://Stackoverflow.com/users/423805', 'pm_score': 2, 'selected': False, 'text': '<p>Thanks to @Vegard for an excellent answer. I cleaned up the code a little bit:</p>\n\n<pre><code>import pandas as pd\nimport numpy as np\n\nclass Point2:\n    def __init__(self,x,y):\n        self.x = x\n        self.y = y\n\nclass Point3:\n    def __init__(self,x,y,z):\n        self.x = x\n        self.y = y\n        self.z = z\n\n# Known 2D coordinates of our rectangle\ni0 = Point2(318, 247)\ni1 = Point2(326, 312)\ni2 = Point2(418, 241)\ni3 = Point2(452, 303)\n\n# 3D coordinates corresponding to i0, i1, i2, i3\nr0 = Point3(0, 0, 0)\nr1 = Point3(0, 0, 1)\nr2 = Point3(1, 0, 0)\nr3 = Point3(1, 0, 1)\n\nmat = [\n    [1, 0, 0, 0],\n    [0, 1, 0, 0],\n    [0, 0, 1, 0],\n    [0, 0, 0, 1],\n]\n\ndef project(p, mat):\n    #print mat\n    x = mat[0][0] * p.x + mat[0][1] * p.y + mat[0][2] * p.z + mat[0][3] * 1\n    y = mat[1][0] * p.x + mat[1][1] * p.y + mat[1][2] * p.z + mat[1][3] * 1\n    w = mat[3][0] * p.x + mat[3][1] * p.y + mat[3][2] * p.z + mat[3][3] * 1\n    return Point2(720 * (x / w + 1) / 2., 576 - 576 * (y / w + 1) / 2.)\n\n# The squared distance between two points a and b\ndef norm2(a, b):\n    dx = b.x - a.x\n    dy = b.y - a.y\n    return dx * dx + dy * dy\n\ndef evaluate(mat): \n    c0 = project(r0, mat)\n    c1 = project(r1, mat)\n    c2 = project(r2, mat)\n    c3 = project(r3, mat)\n    return norm2(i0, c0) + norm2(i1, c1) + norm2(i2, c2) + norm2(i3, c3)    \n\ndef perturb(mat, amount):\n    from copy import deepcopy\n    from random import randrange, uniform\n    mat2 = deepcopy(mat)\n    mat2[randrange(4)][randrange(4)] += uniform(-amount, amount)\n    return mat2\n\ndef approximate(mat, amount, n=1000):\n    est = evaluate(mat)\n    for i in xrange(n):\n        mat2 = perturb(mat, amount)\n        est2 = evaluate(mat2)\n        if est2 &lt; est:\n            mat = mat2\n            est = est2\n\n    return mat, est\n\nfor i in xrange(1000):\n    mat,est = approximate(mat, 1)\n    print mat\n    print est\n</code></pre>\n\n<p>The approximate call with .1 did not work for me, so I took it out. I ran it for a while too, and last I checked it was at </p>\n\n<pre><code>[[0.7576315397559887, 0, 0.11439449272592839, -0.314856490473439], \n[0.06440497208710227, 1, -0.5607502645413118, 0.38338196981556827], \n[0, 0, 1, 0], \n[0.05421620936883742, 0, -0.5673977598434641, 2.693116299312736]]\n</code></pre>\n\n<p>with an error around 0.02. </p>\n'}, {'answer_id': 43801764, 'author': 'Inflight', 'author_id': 2388690, 'author_profile': 'https://Stackoverflow.com/users/2388690', 'pm_score': 0, 'selected': False, 'text': "<p>Yes, Monte Carlo works, but I found better solution for this issue. This code works perfectly (and uses OpenCV):</p>\n\n<pre><code>Cv2.CalibrateCamera(new List&lt;List&lt;Point3f&gt;&gt;() { points3d }, new List&lt;List&lt;Point2f&gt;&gt;() { points2d }, new Size(height, width), cameraMatrix, distCoefs, out rvecs, out tvecs, CalibrationFlags.ZeroTangentDist | CalibrationFlags.FixK1 | CalibrationFlags.FixK2 | CalibrationFlags.FixK3);\n</code></pre>\n\n<p>This function takes known 3d and 2d points, size of screen and returns rotation (rvecs[0]), translation (tvecs[0]) and matrix of intrinsics values of camera. It's everything you need.</p>\n"}]
['https://Stackoverflow.com/questions/76134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8409/']