Autofocus quietly ruins camera calibration

My calibration repo started in December 2023 as a laptop webcam script. In June 2025 it gained a Raspberry Pi version with autofocus switched on.

Code: camera_calibration_with_charuco on GitHub

My calibration repo started in December 2023 as a laptop webcam script. In June 2025 it gained a Raspberry Pi version with autofocus switched on. Going back through it, I found that the autofocus setting undermines the whole calibration, and a few other things had quietly broken along the way.

What calibration is for

Camera calibration measures two things about your camera:

  • the camera matrix: focal length in pixels and where the optical centre sits on the image
  • the distortion coefficients: how much the lens bends straight lines, usually most at the edges

With those, you can undistort images, and more usefully for robots, turn a pixel position into a direction in the real world. If a camera is going to tell an arm where to reach, its calibration is the ruler.

The autofocus problem

Autofocus works by moving the lens. Moving the lens changes the focal length a little. And the camera matrix is the focal length.

The Pi capture script sets AfMode to 2, which is continuous autofocus. So between every calibration image, as you move the board nearer or further, the lens moves too. Each image was taken by a slightly different camera, and calibration tries to find one camera matrix that fits them all. It finds a compromise that’s exactly right for none of them.

It gets worse afterwards. You calibrate, then point the camera at the arm’s workspace, and continuous autofocus moves the lens again for the new distance. The calibration now describes a lens position you’re no longer using. Nothing errors. Measurements are just a bit wrong, and you blame the arm.

Focus once, then lock it

The fix is to focus once, at the distance you’ll actually work at, then switch to manual focus and keep the lens there:

import json
from picamera2 import Picamera2
from libcamera import controls

camera = Picamera2()
camera.configure(camera.create_preview_configuration(main={"size": (1920, 1080), "format": "RGB888"}))
camera.start()

# Focus once, on the board, at the distance you'll work at
camera.set_controls({"AfMode": controls.AfModeEnum.Auto})
if not camera.autofocus_cycle():
    raise RuntimeError("autofocus failed: is the board in view and well lit?")

# Read where the lens ended up, and pin it there
lens_position = camera.capture_metadata()["LensPosition"]
camera.set_controls({"AfMode": controls.AfModeEnum.Manual, "LensPosition": lens_position})

# Save it next to the calibration, so later runs can use the same focus
with open("focus.json", "w") as f:
    json.dump({"LensPosition": lens_position}, f)

LensPosition is in dioptres, which is one divided by the focus distance in metres. 2.0 means 50 cm, 0.5 means 2 m, and 0.0 means infinity.

The calibration file and the focus setting now belong together. Any program that uses the calibration should set the same LensPosition before it trusts a single pixel.

Why a ChArUco board

A plain chessboard only works if every corner is visible, so you can’t push it into the corners of the frame, where lens distortion is strongest. A ChArUco board puts a small ArUco marker in each white square. Every marker has an ID, so OpenCV knows exactly which corner it’s looking at even when half the board is out of view. That’s what makes it good for measuring distortion near the edges.

OpenCV 4.7 broke the script

The original script creates the board like this:

board = cv2.aruco.CharucoBoard_create(sqWidth, sqHeight, 0.035, 0.0175, dictionary)

From OpenCV 4.7, the ArUco code moved into the main library and its API changed. CharucoBoard_create doesn’t exist any more, so the script fails with an AttributeError before reading a single image. The board is now a class, and detection lives in a CharucoDetector.

The board pattern changed too

This one is sneakier. OpenCV 4.6 changed how ChArUco boards with an even number of rows are drawn, and this board has 8 rows. I ran the repo’s own charuco.png through OpenCV 4.10:

Setting Markers found Corners found
default 40 0
setLegacyPattern(True) 40 63

Every marker is detected, so it looks like it’s working, but not a single corner comes back, and calibration has nothing to work with. The board image was made with an older OpenCV, and one line tells the new version to expect the old layout.

The updated script

import glob
import cv2

dictionary = cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50)
board = cv2.aruco.CharucoBoard((10, 8), 0.035, 0.0175, dictionary)  # squares across, down; metres
board.setLegacyPattern(True)  # this board image was made with OpenCV older than 4.6
detector = cv2.aruco.CharucoDetector(board)

object_points, image_points = [], []
image_size = None

for path in sorted(glob.glob("images/*.jpg")):
    gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    image_size = (gray.shape[1], gray.shape[0])  # (width, height), not gray.shape

    corners, ids, _, _ = detector.detectBoard(gray)
    if ids is None or len(ids) < 6:
        print(f"skipping {path}: board not found")
        continue

    obj, img = board.matchImagePoints(corners, ids)
    object_points.append(obj)
    image_points.append(img)

error, camera_matrix, dist_coeffs, _, _ = cv2.calibrateCamera(
    object_points, image_points, image_size, None, None
)
print(f"used {len(object_points)} images, reprojection error {error:.3f} px")

On synthetic images of the repo’s board, rendered with a known camera, this recovers the focal length to within 0.1%.

Two smaller bugs

Width and height. The old script passes img.shape as the image size. NumPy shapes are (height, width), and OpenCV wants (width, height). OpenCV uses that size for its first guess at the optical centre, so the guess starts in the wrong place. The saved YAML also records width and height the wrong way round, which breaks anything that reads them later. The new script builds the tuple explicitly.

Most images were skipped. The old loop only kept an image when a counter was a multiple of 3. With the default 10 images, that’s images 1, 4, 7 and 10: four images used out of ten, and every other position you carefully held the board in was thrown away.

Is the calibration any good?

Two checks:

  • Reprojection error, printed at the end. It’s the average distance, in pixels, between where the corners were detected and where the calibrated model says they should be. Well under one pixel is a good sign. A few pixels means something moved: the board, the focus, or the camera.
  • Straight lines. Undistort an image of something with straight edges (the repo’s verification.py does this) and look at the edges near the corners of the frame. They should be straight.

One last detail: measure your printed board. The 0.035 m square size doesn’t change the focal length in pixels, but it sets the scale of every distance you measure afterwards. If your printer scaled the page, so will your measurements.