TheRare Visuals

Finding someone in every photo, and nobody else

Splitting a shoot's photos and footage by person when several people ask for theirs, with no outside AI service: the licence that ruled out the obvious model, tuning the threshold on wedding makeup, a consent-first design where deletion lives in the database schema, why it now looks at photos only, and the two out-of-memory crashes that real studio photos caused in production.

TheRare Engineering26 November 202616 min readIntermediate

The question

A shoot rarely belongs to one person. A family function, a group of friends, a college batch or a wedding party: several people were photographed together, and afterwards each of them asks us for their photos. A few hundred edited photos, a few thousand originals, and raw footage on top, and somebody on the team has to split it all, person by person, by eye.

That is slow, and it is easy to miss someone in the back of a group shot. So the studio asked a simple question: is there a library that can match a face across our photos, raw footage and editor source footage, so we can split a shoot by person, without sending anything to an AI service?

This post is the answer: what we tried, what the numbers looked like on our own media, and why the privacy rules ended up shaping the database more than the face matching did.

"Without AI" is not quite possible

Every face matcher that works on real photos is a trained model. Older non-learning methods exist (Eigenfaces, LBPH), but they need front-facing, evenly lit faces. Candid wedding shots are neither.

What is possible is running the model ourselves. No API key, no per-call cost, and no face ever leaves our servers. That was the real requirement behind the question, so that is what we built.

The first candidate was InsightFace's ArcFace models, the usual open-source pick and very accurate. Then we read the licence: the pretrained models are for non-commercial research only. A photography studio is a business, so that ruled them out.

We switched to two models from OpenCV's model zoo:

ModelJobLicenceSize
YuNetFinds faces and five landmarks (eyes, nose, mouth corners)MIT0.2 MB
SFaceTurns an aligned face into 128 numbersApache 2.037 MB

How matching works

There are three steps for every image:

  1. Find each face. YuNet returns a box and five landmark points.
  2. Align it. The landmarks are used to rotate and scale the face into a standard 112 by 112 crop, so a tilted head looks like an upright one.
  3. Fingerprint it. SFace turns the crop into 128 numbers. We scale them to length 1, so comparing two faces is a dot product: 1.0 means identical, around 0 means unrelated.
Java
public static float similarity(float[] a, float[] b) {
    float sum = 0f;
    for (int i = 0; i < a.length; i++) {
        sum += a[i] * b[i];
    }
    return sum;
}

Two faces are "the same person" when that score is above a threshold. The whole question is where to put it.

Testing it on our own media first

Before writing any backend code we built a small Python script and ran it over the local copy of our media: 119 photos and 2 raw videos (one frame every 2 seconds, 40 frames). It found 172 faces in about 20 seconds on a laptop.

Then we looked at the results with our own eyes, because a single accuracy number from a paper tells you nothing about your own footage.

TestWhat happened
A groom across his photosAll 16 found, scores 0.69 to 0.76. The next closest person scored 0.36.
An older woman, searched from one video frame21 of her frames found, including blurry and side-on ones down to 0.48. One very dark frame was missed.
Brides in heavy makeupDifferent brides were grouped together at the published threshold.
Babies and young childrenDifferent children grouped together. Unreliable.

SFace's published threshold is 0.363. On our footage it was too generous: bridal makeup and jewellery made different women look alike to the model, and at 0.363 two frames of the older woman also matched a younger woman. At 0.45 the brides separated and every true adult match we checked was still found. So the threshold lives in one place, with a comment saying where the number came from:

Java
/**
 * SFace's published line is 0.363, but tested on TheRare's own media it
 * merged different brides in heavy makeup; 0.45 kept every true match
 * of an adult (0.48 to 0.76) while splitting them.
 */
public static final float MATCH_THRESHOLD = 0.45f;

Children remain a known weakness of models like this. We note it, and we don't pretend otherwise.

One more lesson from the prototype: "use the largest face in the reference photo" is a bad default. Our first search for the groom used a couple's portrait, and the largest face was the bride's. In the real feature, staff click the exact face they mean.

A face fingerprint is biometric data

Here the project changed shape. Those 128 numbers identify a person. Under India's Digital Personal Data Protection Act that needs clear consent, a stated purpose, and a way to delete it. A wedding also has a problem a corporate photo library doesn't: hundreds of guests who never agreed to anything.

So we made three rules before writing the feature:

  1. Consent first. A customer on the booking turns face matching on for themselves, from their own dashboard. It is off by default, and saying no changes nothing about the booking.
  2. Consented people only. We only ever store the fingerprints of people who agreed. Guests' faces are compared and thrown away in the same step.
  3. Deletion that can't be forgotten. Withdrawing consent deletes everything for that person, immediately.

Rule two is the one that most changes the design. The easy version of this feature indexes every face once and searches later. We don't. Staff pick the consenting person's face in one photo, and that one fingerprint is the only one we store. A scan then checks every face it sees against those references and keeps only the matches:

Java
for (FaceEngine.DetectedFace face : faces) {
    // ...find the closest consenting person...
    if (best >= 0 && bestScore >= FaceEngine.MATCH_THRESHOLD) {
        found.add(FaceMatch.builder()
                .personId(people.get(best).getId())
                // which photo, and where in it
                .build());
    }
    // Anyone else's face simply falls out of scope here, never saved.
}

This fits the way we actually use it. When several people ask for their photos, each of them is added to the booking, each turns face matching on for themselves, and staff pick each person's face once. One scan then splits the shoot into a set per person. Someone who didn't ask, and didn't agree, is never looked for.

The cost is real: staff can't later search for a guest who never opted in. We think that is the right trade.

Deletion lives in the schema, not the service

"Delete the face data when X happens" tends to turn into a list of code paths someone has to remember: consent withdrawn, photo deleted, clip moved to another booking, booking deleted, customer deleted. Miss one and you keep biometric data you promised to delete.

So we pushed it into the database. Every face row hangs off something with ON DELETE CASCADE:

SQL
CREATE TABLE face_people (
    id BIGSERIAL PRIMARY KEY,
    booking_id BIGINT NOT NULL REFERENCES bookings(id) ON DELETE CASCADE,
    consent_id BIGINT NOT NULL REFERENCES face_consents(id) ON DELETE CASCADE,
    fingerprint BYTEA NOT NULL,
    ...
);

CREATE TABLE face_matches (
    person_id BIGINT NOT NULL REFERENCES face_people(id) ON DELETE CASCADE,
    media_asset_id BIGINT REFERENCES media_assets(id) ON DELETE CASCADE,
    raw_footage_asset_id BIGINT REFERENCES raw_footage_assets(id) ON DELETE CASCADE,
    ...
);

Withdrawing consent is now one DELETE of the consent row. The database removes the fingerprint and every match in the same statement. Deleting a photo removes its matches. An existing feature that moves raw footage between bookings works by deleting and recreating the row, so it is covered without anyone touching it. We tested this live: one consent, one stored face, 8 matches; delete the consent; zero of each.

On top of that, a nightly job deletes the fingerprints of every delivered or cancelled booking. Once the photos are delivered there is nothing left to find. The consent rows stay, because they hold no face data and they are the record of who agreed and when.

Two more guards:

  • Staff can't consent for a customer. Our "view as customer" support mode is read-only at the server. A PUT to the consent endpoint from that mode gets a 403.
  • Everything is audited. Consent given and withdrawn, faces added and removed, every scan, and every nightly deletion goes to the audit log.

Running it on Cloud Run

Our backend runs on Cloud Run, which only gives an instance CPU while a request is open. Background work that outlives the request gets starved. We learned that the hard way with film previews, so face scanning runs inside requests.

The admin page asks for a list of photos, then sends them to the server one at a time. Each request reads one photo, compares every face in it, saves the matches and returns.

The scan method is deliberately not wrapped in a database transaction. Face detection on a big photo can take a few seconds, and holding a pooled database connection for all of that is how you run out of them. Old matches are cleared and new ones saved in short writes of their own.

We stopped scanning video

The first version scanned video too. A long clip was split into two-minute pieces, ffmpeg pulled one frame every 2 seconds from a signed URL, and each request reported where the next piece should start:

Text
POST /faces/scan { asset: clip 12, fromSecond: 0 }   -> { nextFromSecond: 120 }
POST /faces/scan { asset: clip 12, fromSecond: 120 } -> { nextFromSecond: 240 }
POST /faces/scan { asset: clip 12, fromSecond: 240 } -> { nextFromSecond: null }

Shortly after launch we removed all of that. Face matching now looks at photos only: delivered photos, and photos among the client and editor footage uploads. No frame of any clip is ever looked at.

That narrows what the feature does with people's faces. A two-minute clip at one frame every 2 seconds is 60 pictures, each full of guests whose faces get compared and thrown away; a photo is one. It also took ffmpeg out of the request entirely. The scan list now skips every video, the server refuses a video before reading a byte of it, and a migration deleted every match that had been saved against a clip. The consent wording customers agree to changed from "photos and videos" to photos, so the consent version was bumped with it.

The Alpine surprise

OpenCV for Java ships its native library inside the jar, for Linux and macOS. Our backend image was based on Alpine Linux, which uses the musl C library. The bundled library expects glibc and won't load on Alpine. The fix was to move the runtime image to the Ubuntu-based Java 17 image. That is a bigger change than the feature itself, so it is called out in the commit and checked on the first deploy.

The models aren't committed to git. The Dockerfile downloads them during the build and checks each one against a fixed SHA-256, so a changed file upstream fails the build loudly instead of quietly changing our matches. If the models are missing (say, on a developer's laptop), face matching reports itself unavailable instead of crashing the app on startup.

The first production bug: one photo, one gigabyte

On the day the feature went live, staff tried it on a real booking. They picked a photo, clicked a face, pressed save, and got this in the browser console:

Text
Origin https://therarevisuals.in is not allowed by Access-Control-Allow-Origin.
Status code: 503

It looked like a CORS problem. It wasn't. CORS headers are added by our app, and a 503 with no headers at all means our app never answered. Cloud Run's own logs said why, one second after each failed request:

Text
Memory limit of 1024 MiB exceeded with 1124 MiB used.

Cloud Run had killed the instance in the middle of the request. The pattern was always the same: a fresh instance handled the first face request fine, and died on the second or third.

The photos were the clue. Our studio exports are 7008 by 4672 pixel PNGs, about 31 MB each. Face detection only ever looks at a 1600 pixel version, but the code got there the expensive way:

Java
// Before: decode the whole 33 megapixel picture, then shrink it.
Mat decoded = Imgcodecs.imdecode(new MatOfByte(encodedImage), Imgcodecs.IMREAD_COLOR);

That one line had two problems.

  1. A leak. new MatOfByte(...) copies the 31 MB file into native memory, outside the Java heap. Nothing ever released it. Java's garbage collector would free it eventually, but the collector only runs when the Java heap is under pressure, and this memory isn't on the Java heap. So every request left another 31 MB behind.
  2. A full-size decode. The full picture is about 100 MB of pixels, and over 200 MB at the peak while the PNG is being unpacked, all to be thrown away a moment later when it is shrunk to 1600 pixels.

Picking a face makes two calls on the same photo: one to find the faces, one to save the chosen one. On an instance already holding the app itself, two of those was enough to cross 1 GiB.

The fix decodes no bigger than it has to, and frees what it copies:

  • JPEG files are scaled down while they are decoded. The JPEG format lets the decoder skip straight to a half, quarter or eighth size, so the full picture never exists in memory.
  • PNG files go through Java's own image reader with subsampling: it unpacks the file row by row and keeps only every fourth pixel, which lands at 1752 pixels wide.
  • The native copy of the file is released as soon as it has been read.
Java
MatOfByte buffer = new MatOfByte(bytes);
try {
    return Imgcodecs.imdecode(buffer, flags);
} finally {
    buffer.release(); // free it now, not whenever the collector gets round to it
}

We measured it on one of the real 31 MB photos, running the decode over and over with the Java heap fixed in size so that only native memory showed:

First callNext 6 calls
Before+124 MB+149 MB more, and still climbing
After+105 MB (Java's image libraries loading, once)+16 MB in total

The same photo still gives the same faces, in the same order, every time. That matters more than it sounds: staff pick a face by its position in the list, so the call that finds faces and the call that saves one have to agree.

We also set MALLOC_ARENA_MAX=2 in the Docker image. By default the C memory allocator gives busy threads their own pools and keeps freed memory in each of them, which on a small container looks exactly like a slow leak.

The second production bug: every shape costs 200 MB

The fix shipped, and it helped: an instance went from dying on the second face request to surviving about twenty scans. Then the same 503, the same "Memory limit of 1024 MiB exceeded", this time on /faces/scan, partway through a booking.

So the decode was fixed, and memory still climbed. We ran the whole detection step over our 18 local studio photos, again with the Java heap fixed in size, and printed the native memory after each one:

PhotoShape after shrinkingMemory added
First landscape photo1600 x 1067+235 MB
Next seven landscape photos1600 x 1067about +0
First near-square crop1557 x 1600+209 MB
Everything aftereither shapeabout +0

Nothing grew from photo to photo. It grew from shape to shape. Our code told the face detector each photo's own size before detecting:

Java
detector.setInputSize(new Size(width, height));

The detector is a small neural network, built for 320 by 320 images. Run at 1600 pixels, its working buffers for one input size come to roughly 200 MB, and OpenCV keeps a set for each size it has seen. Landscape photos, portrait photos and the odd crop are three sizes, and a real booking has all of them. A couple of new shapes on a 1 GiB instance that is already running a Spring app is the end of the instance.

The fix is to only ever have one shape. Every photo is shrunk to fit inside a fixed 1280 by 1280 square and placed in its top-left corner, with the rest left black:

Java
// The photo sits in the top-left corner of a fixed square, so a face's
// pixel position is the same in both; boxes are fractions of the photo.
Mat image = new Mat(DETECT_SIZE, DETECT_SIZE, CvType.CV_8UC3, Scalar.all(0));
scaled.submat(0, height, 0, width).copyTo(image.submat(0, height, 0, width));
detector.detect(image, faces);

The detector is set to that size once, when it loads, and never changes. Putting the photo in the corner rather than the middle means a face's pixel position doesn't move, so the boxes we show staff are still simple fractions of the photo.

Over the same 18 photos, the near-square crop now adds +18 MB instead of +209 MB, and memory stays flat after that. Every photo finds the same number of faces as before. We gave up a little resolution to get there: photos were now looked at 1280 pixels across instead of 1600.

That stopped the growth, but not the crashes. Production instances now peaked at 1028 to 1030 MiB: flat, but a few megabytes over the limit, because a Spring app, a full Java heap and the detector's buffers simply add up to about that. The easy answer was a 2 GiB instance. The cheaper one was a smaller square, since the detector's buffers grow with the number of pixels it looks at. We measured three sizes on all 40 photos we had locally, detector and decoding together:

SquareMemoryFaces found
1280+263 MB46
1024+215 MB48
960+196 MB48

The smaller sizes didn't lose a single face. They found two more, and we looked at both: the same man in two copies of one photo, looking down at the ground, which 1280 had missed. We settled on 1024. It saves 48 MB, which should bring the instance back under 1 GiB without paying for a bigger one, and it leaves more detail for small faces in big group shots than 960 would. The smallest face we keep is now 26 pixels, the same share of the picture as the original 40 pixels at 1600.

Where it stands

On a real test booking with 19 files, including raw footage, picking one face and scanning took about 20 seconds. It found the person in 8 files with scores from 0.73 to 1.00, and saved nothing about anyone else.

What we'd tell anyone building something similar:

  • Read the model licence before the model card. The most popular model was the one we couldn't use.
  • Tune the threshold on your own data. The published number was wrong for wedding makeup.
  • Decide what you won't store before deciding what you will. "Consented people only" removed the biggest privacy risk and most of the storage.
  • Make deletion a property of the schema. Cascades don't forget a code path.
  • Count native memory, not just the heap. Image libraries allocate outside Java, where the garbage collector won't save you and Cloud Run will kill you.
  • Measure per input, not per call. Our second leak wasn't a leak: memory grew once for every new photo shape. Feed a model one fixed input size and its memory becomes a constant.
  • Before buying more memory, try a smaller input. Dropping the detector from 1280 to 1024 pixels saved 48 MB and, on our photos, found more faces rather than fewer.

Face matching is now in the admin panel under each booking's Faces tab, looking at photos only, with the results already grouped person by person: that is the split the studio used to do by hand. Customers see the choice on their dashboard, and it is off until they turn it on.

Found this useful?

Built something with what you learned here, or spotted a better way? Tell us. We work with freelance developers on Shootlo.