Structure from Motion: How Ordinary Photos Become 3D (with OpenCV in Python and C++)
Take twenty photos of a building while walking around it. A computer can turn those flat photos into a 3D model, and also work out exactly where you stood for each shot. This is called Structure from Motion (SfM). It is behind Google Earth’s 3D cities, drone surveys of construction sites, 3D scans of temples and statues, and the new wave of 3D Gaussian Splatting scenes.

This post explains SfM for beginners, then shows how developers really use it: with no code, with Python, and with OpenCV in Python and C++.
The idea in one picture

Close one eye and the world looks flat. Open both and you see depth, because each eye sees the same thing from a slightly different place. SfM does the same with photos. If one corner of a window appears in five photos, each photo gives a ray from the camera toward that corner. The rays cross at one spot: the corner’s 3D position. This is called triangulation. Do it for thousands of points, and solve for every camera position at the same time, and you have SfM. The only sensor you need is a camera, so a phone works.
The 5 steps

- Find features. Look for small patches that are easy to find again in another photo: corners, blobs, texture. Classic detectors are SIFT and ORB; SuperPoint is a learned one.
- Match them. Find the same patch in photo A and photo B. A simple trick, Lowe’s ratio test, throws away matches that are not clearly better than the second-best option. LightGlue is a learned matcher that does this very well.
- Camera poses. From the matches, compute how the camera moved between two photos (the essential matrix). RANSAC keeps the matches that agree and ignores the wrong ones.
- Triangulate. Turn each matched pair into a 3D point.
- Bundle adjustment. Adjust all cameras and all 3D points together so that every point lands as close as possible to where it was seen in each photo. This final polish is what makes the model sharp.
Real tools add photos one by one (incremental SfM, slower but very robust) or solve all cameras at once (global SfM, much faster on big photo sets).
How developers use it
1. No code: COLMAP or Meshroom
COLMAP is the standard free tool. Open the GUI, choose Reconstruction → Automatic reconstruction, point it to your photo folder, and wait. From the command line it is the same pipeline, step by step:
colmap feature_extractor --database_path db.db --image_path photos
colmap exhaustive_matcher --database_path db.db
mkdir sparse
colmap mapper --database_path db.db --image_path photos --output_path sparse
# faster on large photo sets: the global mapper (GLOMAP, built into COLMAP 4)
# colmap global_mapper --database_path db.db --image_path photos --output_path sparse
Meshroom is a free GUI that goes all the way from photos to a textured mesh with one click.
2. Python: pycolmap
The same COLMAP pipeline from Python (pip install pycolmap):
import pathlib, pycolmap
out = pathlib.Path("out"); out.mkdir(exist_ok=True)
db = out / "database.db"
pycolmap.extract_features(db, "photos")
pycolmap.match_exhaustive(db)
maps = pycolmap.incremental_mapping(db, "photos", out)
maps[0].write(out)
print(maps[0].summary())
3. Build it yourself with OpenCV (Python)
The best way to understand SfM is to write the two-view version yourself. This script does steps 1 to 4 for two photos and saves a 3D point cloud you can open in MeshLab or CloudCompare. I tested it with OpenCV 5.1.
# Two-view Structure from Motion with OpenCV (Python). Usage: python sfm_two_view.py img1.jpg img2.jpg
import sys
import cv2
import numpy as np
img1 = cv2.imread(sys.argv[1], cv2.IMREAD_GRAYSCALE)
img2 = cv2.imread(sys.argv[2], cv2.IMREAD_GRAYSCALE)
# Camera intrinsics: use your calibration (cv2.calibrateCamera); this is a rough guess
h, w = img1.shape
f = 1.2 * w
K = np.array([[f, 0, w / 2], [0, f, h / 2], [0, 0, 1]])
# 1) Features
sift = cv2.SIFT_create(4000)
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# 2) Matching + Lowe's ratio test
matches = cv2.BFMatcher().knnMatch(des1, des2, k=2)
good = [m for m, n in matches if m.distance < 0.75 * n.distance]
p1 = np.float64([kp1[m.queryIdx].pt for m in good])
p2 = np.float64([kp2[m.trainIdx].pt for m in good])
# 3) Relative camera pose (essential matrix + RANSAC)
E, mask = cv2.findEssentialMat(p1, p2, K, method=cv2.RANSAC, prob=0.999, threshold=1.0)
n_ok, R, t, mask = cv2.recoverPose(E, p1, p2, K, mask=mask)
inl = mask.ravel() > 0
# 4) Triangulation
P1 = K @ np.hstack([np.eye(3), np.zeros((3, 1))])
P2 = K @ np.hstack([R, t])
X = cv2.triangulatePoints(P1, P2, p1[inl].T, p2[inl].T)
X = (X[:3] / X[3]).T # 3D points, scale unknown (|t| = 1)
print(f"{len(good)} matches, {inl.sum()} inliers, {len(X)} 3D points")
np.savetxt("points.xyz", X) # open in MeshLab / CloudCompare

To check the code, I made a synthetic photo pair: two textured walls, one at depth 4 and one at depth 6, seen from two camera positions. The script found 2,805 matches, kept 2,803 after RANSAC, and placed the two walls at a depth ratio of 1.50, exactly the true value. On synthetic points with known truth, the recovered rotation was within 0.2°.
4. The same steps in C++
#include <opencv2/opencv.hpp>
int main(int argc, char** argv) {
cv::Mat img1 = cv::imread(argv[1], cv::IMREAD_GRAYSCALE);
cv::Mat img2 = cv::imread(argv[2], cv::IMREAD_GRAYSCALE);
double f = 1.2 * img1.cols; // use your calibrated K
cv::Mat K = (cv::Mat_<double>(3, 3) << f, 0, img1.cols / 2.0, 0, f, img1.rows / 2.0, 0, 0, 1);
auto sift = cv::SIFT::create(4000);
std::vector<cv::KeyPoint> k1, k2; cv::Mat d1, d2;
sift->detectAndCompute(img1, cv::noArray(), k1, d1);
sift->detectAndCompute(img2, cv::noArray(), k2, d2);
std::vector<std::vector<cv::DMatch>> knn;
cv::BFMatcher(cv::NORM_L2).knnMatch(d1, d2, knn, 2);
std::vector<cv::Point2d> p1, p2;
for (auto& m : knn)
if (m[0].distance < 0.75f * m[1].distance) {
p1.push_back(k1[m[0].queryIdx].pt);
p2.push_back(k2[m[0].trainIdx].pt);
}
cv::Mat mask, R, t;
cv::Mat E = cv::findEssentialMat(p1, p2, K, cv::RANSAC, 0.999, 1.0, mask);
cv::recoverPose(E, p1, p2, K, R, t, mask);
cv::Mat P1 = K * cv::Mat::eye(3, 4, CV_64F), Rt;
cv::hconcat(R, t, Rt);
cv::Mat P2 = K * Rt, X;
cv::triangulatePoints(P1, P2, p1, p2, X); // 4xN homogeneous; divide by row 3
std::cout << p1.size() << " matches, " << cv::countNonZero(mask) << " inliersn";
}
For a full multi-photo pipeline in C++, use COLMAP or OpenMVG as a library instead of writing bundle adjustment yourself.
Which tool should I use?

- Just want a 3D model: phone photos + COLMAP or Meshroom.
- Want to learn: the OpenCV two-view code above.
- Hard photos (night, few textures, big viewpoint changes): learned features and matching (SuperPoint + LightGlue, via the hloc toolbox), which feed into COLMAP.
- Very few photos or no calibration: MASt3R or VGGT, deep networks that predict cameras and 3D points almost directly.
- Beautiful viewing: run SfM first, then train 3D Gaussian Splatting on its cameras and points.
Lessons from testing it myself
- SfM cannot know the real size. A model of a 1 m object and a 10 m object look the same. Put a ruler or a marker of known size in the scene if you need real measurements.
- Move sideways, do not just turn. If you rotate the camera on the spot, there is no 3D information at all. In my test that gave 2,588 matches but only 1 usable 3D point.
- Calibrate your camera. Wrong focal length or lens distortion quietly bends the whole model.
cv2.calibrateCamerawith a printed checkerboard takes ten minutes. - Take good photos. About 70% overlap between neighbouring photos, steady light, no moving people or cars, and extra angles on plain white walls.
Start with phone photos and COLMAP. Learn with the OpenCV code. Then show off with 3D Gaussian Splatting.
Sources and further reading
- IZUTSUYA Inc., SFM(Structure from Motion)完全ガイド (note.com, 2026), the article that started this post
- Schönberger & Frahm, Structure-from-Motion Revisited, CVPR 2016 (COLMAP); COLMAP documentation
- Pan et al., Global Structure-from-Motion Revisited (GLOMAP), ECCV 2024
- Lindenberger et al., LightGlue, ICCV 2023; DeTone et al., SuperPoint, CVPR Workshops 2018
- Wang et al., VGGT: Visual Geometry Grounded Transformer, CVPR 2025
- OpenCV tutorial: epipolar geometry
- Hartley & Zisserman, Multiple View Geometry in Computer Vision, the classic textbook
All images in this post are made with code. Image 3 is a real run of the Python code above on a synthetic image pair, not real photos.

Commentaires · 3
The useful reminder is that Structure from Motion is not one photo: you walk around a building, each corner appears in several shots, and the rays meet at a 3D point — a phone is enough, but you need multiple viewpoints. I built Image to STL, which takes a single image or a text description and generates a full 3D model you can export as STL, OBJ or GLB — not a heightmap. It will not recover camera positions from a set of survey photos the way SfM does, and a mesh from one picture still has to be checked before you treat it like a scanned building.