Point a camera at a building. The model suggests a landmark and a marker appears on the map. What observation put the marker at those coordinates?

Location Intelligence, part 3 of 4.

As a demo it is convincing. The engineering is hidden in the half second between the recognition and the marker, where three quiet substitutions took place. A label became a specific place. A score became a certainty. A rectangle in an image became a position on the Earth. Each substitution is an inference with its own error rate, and the demo code performs all three in one line that assigns a coordinate.

Edition 36 and part 2 of this series treated a GPS fix and a photo's metadata as evidence to be weighed before the app states anything. A model's output deserves the same treatment with more caution, because it is fluent: it always returns an answer, formatted exactly like a correct one.

Four stages that should stay separate

"The app recognized the place" compresses four different steps:

  • Detection: something occupies this region of the image.
  • Classification: the model associates this region with these labels, at these scores.
  • Entity resolution: the evidence points to this particular entry in a catalog of places.
  • Geographic placement: that entry has coordinates, which come from the catalog and not from the camera.

A model that outputs "clock tower" has done the second step. Which clock tower, of the several hundred in the catalog, is the third, and it needs other evidence: where the device is, which way it faces, what else is in frame. Where that tower is located is the fourth, and its answer is a database lookup with its own provenance.

Collapsing these into a property like recognizedPlace: CLLocationCoordinate2D discards every piece of information needed to decide whether to believe the result. So the values stay separate:

SwiftGitHub
import Foundation
import CoreGraphics

struct VisualClassification: Equatable, Sendable {
    let label: String
    let score: Float
    let modelVersion: String
    let frameID: UUID
}

struct CatalogPlace: Identifiable, Equatable, Sendable {
    let id: String
    let name: String
    let labels: Set<String>
    let latitude: Double
    let longitude: Double
}

struct PlaceCandidate: Equatable, Sendable {
    let place: CatalogPlace
    let classification: VisualClassification
    let distanceMeters: Double?
}

enum PlaceResolution: Equatable, Sendable {
    case match(PlaceCandidate)
    case choices([PlaceCandidate])
    case unknown
}

CatalogPlace.id comes from the app's catalog. The model's label is text, and using model text directly as a database key is how an app ends up with a place called "castle" at latitude zero. modelVersion and frameID travel with the classification so that a result can be traced to the model and the frame that produced it, which matters the first time someone asks why the app said what it said.

A resolver with a stated policy

Entity resolution is where visual evidence and location evidence meet, and it should be a function with rules a reviewer can read:

SwiftGitHub
struct ResolutionPolicy: Sendable {
    let minimumScore: Float
    let maximumDistanceMeters: Double
    let maximumChoices: Int
}

func resolvePlace(
    classifications: [VisualClassification],
    catalog: [CatalogPlace],
    distanceToPlace: (CatalogPlace) -> Double?,
    policy: ResolutionPolicy
) -> PlaceResolution {
    var candidates: [PlaceCandidate] = []

    for classification in classifications
    where classification.score >= policy.minimumScore {
        for place in catalog where place.labels.contains(classification.label) {
            let distance = distanceToPlace(place)
            if let distance, distance > policy.maximumDistanceMeters { continue }
            candidates.append(PlaceCandidate(
                place: place,
                classification: classification,
                distanceMeters: distance
            ))
        }
    }

    var seen = Set<String>()
    let unique = candidates
        .sorted { $0.classification.score > $1.classification.score }
        .filter { seen.insert($0.place.id).inserted }

    switch unique.count {
    case 0:
        return .unknown
    case 1:
        return .match(unique[0])
    default:
        return .choices(Array(unique.prefix(policy.maximumChoices)))
    }
}

The policy has three properties worth defending.

.unknown is a first-class result. A resolver that always returns its best guess is correct exactly as often as the model happens to be, and gives the UI no way to tell the difference. Most of what a camera sees in the world is not in any catalog.

Ambiguity is shown, not hidden. Two places with the same label within range produce .choices. Presenting three plausible places and letting the person tap one is frequently a better product than a single confident marker that is wrong one time in five.

Location filters candidates and never proves one. Being 200 meters from a landmark makes it a plausible subject. It does not show the camera is pointed at it. The phone may be aimed at a poster, a television, a model in a souvenir shop, or a different building that looks similar. The device's position may itself be stale or coarse, which was the subject of edition 36. When distanceToPlace returns nil because no usable fix exists, the resolver keeps the candidate and records that distance was not considered.

What the policy does not do is combine the score and the distance into one number. Multiplying a classifier score by a proximity weight produces a value that looks like a probability and has no defined meaning. If you do build a combined ranking, treat it as a new model: document it and evaluate it against labeled data like any other.

A score is not a probability until you have checked

A classifier's 0.9 does not mean nine in ten such predictions are correct for your users. It is the model's output on a scale that was shaped by its training data, and how well it matches real accuracy has to be measured on data from your own domain. That measurement is called calibration, and it is not difficult to do:

SwiftGitHub
struct LabeledPrediction: Sendable {
    let score: Float
    let wasCorrect: Bool
}

func precision(
    atOrAbove threshold: Float,
    in predictions: [LabeledPrediction]
) -> (precision: Double, coverage: Double)? {
    let accepted = predictions.filter { $0.score >= threshold }
    guard !accepted.isEmpty, !predictions.isEmpty else { return nil }

    let correct = accepted.count { $0.wasCorrect }
    return (
        Double(correct) / Double(accepted.count),
        Double(accepted.count) / Double(predictions.count)
    )
}

Run the model over a labeled evaluation set, then call this for a range of thresholds. Each threshold gives a pair: of the predictions accepted, how many were right, and what share of all inputs was accepted at all. Raising the threshold raises precision and lowers coverage. Somewhere on that curve is the point the product can live with, and minimumScore should be that number, with the evaluation that produced it recorded next to it.

The evaluation set decides whether the number means anything. It needs the conditions your users are in: dusk, rain, backlight, a tilted phone, a dirty lens, partial occlusion. It needs, above all, plenty of images of things that are not in the catalog at all, because those are what the camera will mostly see and what a closed-set classifier is worst at rejecting.

Weigh the two kinds of error by their consequences. A wrong suggestion in a travel journal costs a tap. A wrong landmark in a navigation instruction sends someone down the wrong street.

Coordinate transforms deserve their own tests

Before any of this reaches a map, there is usually an overlay: a box drawn around the detected object in the camera preview. It is the part of the feature most often wrong by a small amount, and the cause is nearly always a skipped coordinate conversion.

Vision reports rectangles in a normalized space, 0 to 1 on each axis, with the origin at the bottom left. UIKit and SwiftUI put the origin at the top left. The preview is typically scaled to fill the view, which crops the image. So there are at least two conversions, and each can be written and tested as a pure function:

SwiftGitHub
func topLeftImageRect(
    normalizedBottomLeft rect: CGRect,
    imageSize: CGSize
) -> CGRect {
    CGRect(
        x: rect.minX * imageSize.width,
        y: (1 - rect.maxY) * imageSize.height,
        width: rect.width * imageSize.width,
        height: rect.height * imageSize.height
    )
}

func aspectFillViewRect(
    imageRect: CGRect,
    imageSize: CGSize,
    viewSize: CGSize
) -> CGRect {
    let scale = max(
        viewSize.width / imageSize.width,
        viewSize.height / imageSize.height
    )
    let offsetX = (viewSize.width - imageSize.width * scale) / 2
    let offsetY = (viewSize.height - imageSize.height * scale) / 2

    return CGRect(
        x: imageRect.minX * scale + offsetX,
        y: imageRect.minY * scale + offsetY,
        width: imageRect.width * scale,
        height: imageRect.height * scale
    )
}

The first function flips the vertical axis and scales to pixels. Vision provides the same conversion, as VNImageRectForNormalizedRect in the older API (which keeps the bottom-left origin) and as NormalizedRect.toImageCoordinates(_:origin:) in the Swift API, where passing .upperLeft does the flip for you. I keep my own version only where I want the conversion visible in a test.

The second maps image pixels into a view that displays the image scaled to fill. With aspect-fill, one axis overflows the view and is cropped equally on both sides, so its offset is negative. Leaving that offset out is the usual reason boxes drift further from their objects toward the edges of the screen.

These two functions assume an upright, unmirrored image. Real pipelines add the buffer's orientation, front-camera mirroring, and any region of interest or crop-and-scale option set on the request. Apply every transform explicitly and in order. A rectangle can be numerically valid at each step and still land on the wrong object because one frame of reference was skipped.

The cheapest test uses no model at all. Feed the functions the four corners and the center of the normalized square and check where they land for a portrait image in a landscape view and the reverse. Then, on a device, point the camera at a printed sheet with a marker in each corner and draw the computed rectangles. If the markers and the boxes line up, the geometry is right, and whatever is wrong afterwards is the model.

Bound the work before it becomes latency

A camera delivers 30 or 60 frames per second. If inference takes 80 milliseconds and the capture callback starts a new Task for every frame, the backlog grows by several frames a second. Memory rises, the device heats up, and the box on screen shows where the object was three seconds ago.

For interactive recognition, old frames have no value. The policy I use is one inference in flight and one pending slot that newer frames overwrite:

SwiftGitHub
actor LatestFrameProcessor<Frame: Sendable, Output: Sendable> {
    private let infer: @Sendable (Frame) async -> Output
    private let deliver: @Sendable (Output, _ sessionID: UInt64) async -> Void

    private var pending: (frame: Frame, sessionID: UInt64)?
    private var isRunning = false
    private(set) var droppedFrameCount = 0

    init(
        infer: @escaping @Sendable (Frame) async -> Output,
        deliver: @escaping @Sendable (Output, _ sessionID: UInt64) async -> Void
    ) {
        self.infer = infer
        self.deliver = deliver
    }

    func submit(_ frame: Frame, sessionID: UInt64) {
        if pending != nil { droppedFrameCount += 1 }
        pending = (frame, sessionID)

        guard !isRunning else { return }
        isRunning = true
        Task { await drain() }
    }

    private func drain() async {
        while let next = pending {
            pending = nil
            let output = await infer(next.frame)
            await deliver(output, next.sessionID)
        }
        isRunning = false
    }
}

Whatever the frame rate, at most two frames are alive in the pipeline, and the result on screen is never more than one inference behind the camera. droppedFrameCount is there so the drop rate can be reported; a number that climbs after a model update tells you the new model is slower before a user does.

In a test with a 10 millisecond stand-in for inference, submitting 200 frames as fast as possible resulted in a handful of inferences, with the final frame always among them. That last property is the important one for an interactive feature: when the camera stops moving, the last thing it saw gets processed.

This is the right policy for a live viewfinder and the wrong one for analyzing a recorded video, where every frame matters. There the pipeline needs back-pressure and progress reporting. The queue discipline follows from the product requirement, and neither Vision nor Core ML chooses it for you.

Results must still belong to the current session

The user flips to the front camera, switches models, or leaves the screen while an inference is running. Its result arrives afterwards.

That is why every frame above carries a sessionID, and why deliver receives it back. The consumer compares it with the current session before publishing anything. Cancelling the task is worthwhile to save work, but a Core ML prediction that has already started will generally run to completion, so the comparison is what keeps a result from the previous camera off the current screen.

The same reasoning applies to caching. A cached result is only reusable if the image, the model version, and the preprocessing (crop, orientation, scale) all match. The same pixels run through a newer model are a different question.

Performance is something you measure on a device

Core ML decides at load time how to run a model across CPU, GPU, and Neural Engine, based on the model's operations, the device, and the configuration. Setting computeUnits expresses what the system is allowed to use. It does not guarantee that a given layer runs on a given accelerator, and an unsupported operation can move part of the model to the CPU.

So measure the whole path on the hardware you support: capture, preprocessing, inference, postprocessing, and the UI update. A fast model inside a pipeline that converts pixel formats twice is a slow feature. Measure sustained use as well as the first inference; after several minutes of camera plus inference, thermal throttling can change the numbers considerably. Any latency figure you publish needs the device model, OS version, and model version next to it.

Make the visible claim match the evidence

"Possible match" and "You are at the clock tower" are different product statements, and the resolution type already distinguishes them. Let the UI follow it: a confirmed marker for a .match the user accepted, a short list for .choices, and a plain "not recognized" for .unknown.

Keep raw model output available for diagnostics in controlled builds. Do not start collecting users' camera frames and location traces because they would make debugging easier. An evaluation set built from synthetic and consented images, with a documented retention period, serves that purpose without turning a recognition feature into a surveillance dataset.

What to ask of your own feature

  • Where does a label turn into a specific place, and what evidence supports that step?
  • Can the resolver return "unknown", and does the UI have a state for it?
  • Where did the score threshold come from, and on what data?
  • Is each coordinate conversion a tested function, including the crop?
  • How many frames can be in flight at once, and what happens to a result from a previous session?

Part 4 takes a place that has been selected with all this care and presents it in an immersive scene, where the question becomes who owns the place when the scene goes away.

References

If this edition sharpened your next review, you can buy me a coffee.