如何把真實太陽位置繪入手機照片,將平均誤差降至 1.9°
Drawing the real sun into a phone photo, to within 2 degrees
開發者把定位勘景 Windows 應用程式中的太陽路徑標示平均誤差,從 4.3° 降至 1.9°,最差誤差則由 8.2° 降至 2.8°。校正包括利用照片記錄的重力向量計算相機傾斜,以及修正視角計算中的焦距與照片方向問題;時區偏差也會令太陽位置出錯。
I make a Windows app for location scouts, the people who find streets and buildings for film shoots. They take hundreds of phone photos of a place, and the first question back at the office is always about light: is that façade lit in the morning or the evening, and is the sun in shot when the crew can get there?
So the app has a key, S, that draws the sun's path into the photo: today's arc with the hours marked, plus the June and December solstices and the equinox, so you can see how high and low the sun gets over the year.
The first version looked right and was wrong. Against photos with the real sun in the frame it was 4.3° off on average and 8.2° at worst. That's more than the sun's own width many times over, enough to put it on the wrong side of a chimney. This post is about what it took to get to 1.9° average, 2.8° worst, roughly in the order each fix mattered.
The easy part: where the sun is
The sun's azimuth and elevation for a place and a moment have a closed-form answer. I used the formulas behind NOAA's solar calculator (from Jean Meeus's Astronomical Algorithms): Julian century, mean longitude and anomaly, equation of centre, obliquity, equation of time, hour angle, then a refraction correction near the horizon. It's about 60 lines of standard-library Python, with no dependencies and no network, so it works offline forever. It matches published sunrise and sunset times to within about two minutes.
None of my errors came from there. They all came from the camera.
Putting the sun on a pixel
Once you know where the sun is in the sky, you need to know where the camera was pointing and how wide it saw. The projection is a plain pinhole: turn the sun's direction into camera axes and divide by depth.
function project(az, el, cam) {
var rel = wrap180(az - cam.yaw) * D, e = el * D, p = (cam.pitch || 0) * D;
var ce = Math.cos(e);
var X = ce * Math.sin(rel), Y = Math.sin(e), Z = ce * Math.cos(rel);
var Zc = Y * Math.sin(p) + Z * Math.cos(p); // depth after the pitch
if (Zc <= 1e-9) return null; // behind the camera
var Yc = Y * Math.cos(p) - Z * Math.sin(p);
var t = turn({ tx: X / Zc, ty: Yc / Zc }, cam, 1); // roll, in the image plane
return fromTan(t.tx, t.ty, cam); // tangents -> 0..1 of the frame
}
My first version was linear in angle (x = rel / hfov). That's fine for one dot near the middle of the frame, but an arc has to bend toward the edges, and a linear mapping can't do that. Two details matter here. A point behind the camera has to break the line, not be clamped to the edge, or the arc draws a chord straight across the sky. And roll is the last rotation, applied in the image plane, so the horizon stays straight under any roll.
The inputs are yaw (the compass heading), pitch, roll and the field of view. Each one turned out to be wrong in its own way.
Fix 1: the camera wasn't level
The first version assumed the phone was held level. People don't hold it level, and scouts point down at streets and up at rooftops. The median tilt in my own test library was 8°, and every degree of pitch moves the sun a degree up or down the frame.
It turns out an iPhone records which way was down. Apple's maker note, tag 0x0008, holds the gravity vector at the moment of capture, in g, in the phone's own axes. The lens looks along −Z, the sensor's down is −X and its right is −Y. I worked those axes out from real photographs, one held landscape and one portrait, because I couldn't find them documented anywhere.
def attitude_from_gravity(g, orientation):
x, y, z = (float(c) for c in g)
n = math.sqrt(x * x + y * y + z * z)
pitch = math.degrees(math.asin(max(-1.0, min(1.0, z / n))))
# gravity across the sensor, turned into the photo *as displayed*
du, dv = _DISPLAY_FROM_SENSOR[orientation or 1](-y, -x)
if math.hypot(du, dv) / n < 0.05: # pointing almost straight up or down
return pitch, 0.0
return pitch, math.degrees(math.atan2(du, dv))
Axes you've guessed from two photos need checking, and I wanted a check that didn't share any assumptions with the code. Two consecutive frames taken from the same spot differ by a pure rotation. Match features between them (SIFT, then a homography H), and the rotation falls out as R = K⁻¹ H K, where K is the camera matrix. Compare that with the rotation between the two gravity readings. Across 83 frame pairs they agreed to under a degree. With roll's sign flipped the disagreement doubled, and with pitch's sign flipped it was twenty degrees. That's how I know the signs are right, not just that the tests pass.
Front cameras look out of the other face of the phone, so their gravity isn't used. Mirrored EXIF orientations (2, 4, 5, 7) come from front cameras, so those are skipped too.
Fix 2: the field of view was 16° too wide
EXIF gives you FocalLengthIn35mmFilm, and I assumed that meant a frame 36 mm wide. It doesn't. A 35mm-equivalent focal length matches the diagonal, 43.27 mm, and a phone's frame is 4:3, not 3:2.
def fov_for(f35, aspect):
f = float(f35)
w = 43.27 / math.sqrt(1 + 1 / (aspect * aspect)) # frame width at the photo's aspect
h = w / aspect
return (2 * math.degrees(math.atan(w / (2 * f))),
2 * math.degrees(math.atan(h / (2 * f))))
For a landscape 4:3 frame, assuming 36 mm across was two degrees too wide, a small error. For a portrait frame it was sixteen, because the narrow side is the one across. There was a second bug hiding in the same place: I read the image size before applying the EXIF orientation, so a portrait photo (orientation 6 or 8) reported a landscape aspect. You can't see that on a single dot in the middle. Once a whole arc is drawn, it's obvious.
Fix 3: some clocks were an hour out
The sun moves about 15° an hour, so the time zone has to be exactly right. Photos store local time. The first version read OffsetTimeOriginal when the photo had it, and recent phones write it. Photos without it fell back to a guess from longitude, which put Athens in August an hour out. Now there are three sources, tried in this order:
-
OffsetTimeOriginal. It's exact. -
The GPS block's own UTC timestamp, compared with the local capture time. It's also exact, and it includes summer time, with no time-zone database needed. That matters because Python's
zoneinfoon Windows has no system data to read. - Longitude, as a last resort, and it's only a guess. It puts Athens in August at UTC+2 when it's +3, and Madrid at 0 when it's +2 all summer.
The GPS clock gets a sanity check: the offset it implies has to land within minutes of an offset that actually exists somewhere. Otherwise a stale GPS fix can invent a time zone of +3:43. When the app does fall back to longitude, the overlay says "time zone guessed", because no calibration can fix that error.
Fix 4: true north
The sun is placed against true north, but some phones write the heading against magnetic north (GPSImgDirectionRef = "M"). My iPhone writes true north, so this one didn't change my numbers, but other phones need it. I implemented the World Magnetic Model (WMM2025), again in standard-library Python, and tested it against NOAA's hundred published test values.
Checking it against the real sun
Unit tests can tell you the code does what you meant. They can't tell you that what you meant is right. So I measured against the actual sun. I picked five photos with the sun in the frame, found the saturated blob (connected components on pixels where every channel is at least 250), and compared its centre with where the overlay put it. The overlay was rendered by the app's real front end in headless Playwright, not by a reimplementation.
| Mean error | Worst | |
|---|---|---|
| First version (level camera, 36 mm across) | 4.3° | 8.2° |
| With the phone's tilt and roll, and the diagonal field of view | 1.9° | 2.8° |
That's with no calibration at all, straight from what the phone recorded. These five photos all had OffsetTimeOriginal, so the time-zone fix doesn't show up in this table. It matters for photos that don't carry it.
What's left: the compass
Most of the remaining error is the phone's compass: 2–3° per photo as a rule, with occasional jumps of 8–13° near metal. The worst photos in my set were taken from a balcony with an iron railing.
You can't fix that from the photo's data, so the app lets you fix it by hand. If the sun is in the frame, click it, and the heading is solved exactly from the sun's known position. If it isn't, draw along a shadow on level ground. The shadow version has a trap I walked straight into: when the sun is in front of the camera, shadows run toward you, and their vanishing point is the sun's own, not the point opposite it. Pick the wrong one and the heading comes out 180° off, for half of all photos. The solver now checks which way the drawn shadow runs relative to the horizon before choosing.
Things I'd tell myself at the start
- Measure against the world, not against your own expectations. Each of these bugs had passing tests. The frame-pair rotations and the real-sun photos are what found them.
- Draw the whole curve. A single dot near the centre hid the projection bug, the portrait field of view and the orientation swap. All three showed up as soon as an arc ran edge to edge.
- Render once. "Save annotated copy" re-renders the same SVG at full size in the browser and only composites it on the Python side. A second renderer in Pillow would slowly drift from the one on screen, and the whole point is that the saved file matches what you checked.
The app is Location Sorter. It sorts folders of phone photos into places by GPS, and the sun overlay is one part of it. It's Windows-only, in the Microsoft Store, with a 7-day free trial. I built it with Claude Code as a pair programmer, and Claude helped draft this post. The measurements, the photos and the mistakes are mine.
Happy to answer questions about any of the maths, or the parts of iPhone EXIF that aren't documented.
來源:DEV Community · dev.to
