Your capture loop saves face crops as 1b2e2eb9-5a0f-4875-9fb9-27da545fc711.png, the files sit in the folder, and the LBPH trainer (Local Binary Patterns Histograms) then reads none of them, or dies on an empty training list. The same crops trained fine when the writer produced image_r_00000.png names, so the suspicion falls on the UUID. The UUID is innocent. This page is for engineers building face enrollment and training pipelines in Python with OpenCV, capturing from smart cameras or 3D sensors. You will separate the three places the chain breaks — the write, the name, the pattern that selects files for training — run a three-number preflight that points at the broken one, and then decide whether to keep random names or switch to a padded counter.
What actually fails when your training folder is full of UUID-named PNGs?
The write succeeds, the files sit on disk, and the trainer sees none of them: a glob or regex built for image_r_00000.png matches a name like 1b2e2eb9-5a0f-4875-9fb9-27da545fc711.png zero times, so LBPH trains on an empty list or errors out.
The symptoms arrive in a fixed order. First, len(glob.glob('dataset//image_r_.png')) prints 0 while the folder holds hundreds of files. Next, train() raises a cv2.error because the image and label lists are empty or mismatched. If a stale subfolder still holds a few old pattern-named files, the model trains instantly and then predicts the same label for everyone, because it learnt from three leftover images instead of 1,800 current ones. Nothing is wrong with the camera, the crop code or the recognizer. The selection step between disk and training is the only link that changed. The upstream sibling — cv2.imwrite raising an assertion because the frame it received is empty — has its own fix in cv2 imwrite assertion failed: fix the frame first.
Is the UUID string itself the problem?
No: a PNG file's name is bytes to cv2.imread, and a UUIDv4 name is 36 characters of ASCII letters, digits and hyphens with no reserved characters, so every file system accepts it; the recognizer never parses names, your loader's selection pattern does, and that is where the match fails.
A uuid4() value is 122 random bits printed as eight-four-four-four-twelve hex digits. It contains no colon, no slash and no space — the characters file systems actually refuse. A timestamp-style name such as 12:30:45.png fails on Windows, where the colon is reserved; the UUID writes cleanly everywhere.
LBPH reads pixels, not names. It never sees the string, and the histograms it builds are identical whatever the file is called. If you can open one of these files in an image viewer and it shows a face, the name has passed every check the recognizer cares about. The fault sits one step away, in the code that decides which files count as training data.
Which filename pattern does your dataset loader actually match?
Count what the pattern matches before you train: glob.glob('dataset//image_r_.png') returns 0 files when the folder holds UUID names, because the literal prefix image_r_ and its underscore never appear in a UUID string.
The padded writer your pipeline used to run produces exactly the names the loader was built around. 'dataset/person_01/image_r_{}.png'.format(str(i).zfill(5)) writes image_r_00000.png through image_r_00149.png for 150 crops. Two selection styles match those names: a glob such as image_r_*.png keys on the literal prefix, and a regex such as image_r_(\d{5}).png additionally demands exactly five digits after it.
A UUID name fails both at once. It has no image_r_ prefix, and its digits arrive in runs of eight, four, four, four and twelve, separated by hyphens, so \d{5} never finds a five-digit run to grip. If you hand-roll filename regexes, anchor both ends and test against a real directory listing; the classic mistakes are in regex matches only the first character: anchors and terminators.
| Loader pattern | image_r_00000.png | UUID-named file |
|---|---|---|
| glob 'dataset//image_r_.png' | match | no match |
| regex image_r_(\d{5}).png | match | no match |
| walk with rglob('*.png') | match | match |
Did the file your loop meant to write ever reach the disk?
cv2.imwrite signals failure with a False return instead of an exception, and a missing parent folder is the classic trigger: create the folder first and check every write, because nothing on disk later makes imread return None for all your files.
The one-line writer behind this failure packs three operations into an f-string: cv2.imwrite(f'{_username / Path(str(uuid.uuid4()))}.png', face_resize). The / join only works when _username is a Path object; with a plain string it raises TypeError before any write happens. And a folder that was never created surfaces as a False return value, so the loop runs to the end and saves nothing. Build the path in steps and make the write checkable:
from pathlib import Path
import uuid
import cv2
person = "person_01" # str: folder name under dataset/
out_dir = Path("dataset") / person # Path
out_dir.mkdir(parents=True, exist_ok=True)
path = out_dir / f"{uuid.uuid4()}.png" # Path
ok = cv2.imwrite(str(path), crop) # crop: numpy uint8, 200 x 200; ok: bool
if not ok:
raise IOError(f"imwrite failed: {path}")
Two quieter path traps sit behind this one. Separator direction, drive letters and case behave differently across operating systems; the failure set is worked through in Python image file path errors across operating systems. If a user folder name carries accented characters, rename the dataset folder to plain ASCII and rerun the capture: if writes start succeeding, the characters were the problem, and an ASCII folder name costs nothing. The two checks that close the loop are Path(path).exists() after the write and a None return from imread before training.
How do you prove what the trainer will read before training starts?
Print three numbers before you call train: files written, files your selection pattern matches, and files imread actually opens; in a 12-person dataset at 150 crops each that is 1,800 written, and any gap between 1,800 and the matched count is the bug.
The counts separate the three suspects. Written but unmatched means the pattern. Written but unloadable means pixels or extension. Missing entirely means the write never happened.
from pathlib import Path
import cv2
written = sorted(Path("dataset").rglob("*.png")) # list[Path]: everything on disk
matched = [p for p in written if p.name.startswith("image_r_")]
unloadable = [p for p in written if cv2.imread(str(p)) is None]
print(len(written), len(matched), len(unloadable)) # healthy run: 1800 1800 0
The same walk-and-load loop, extended to log pixel values per file, is in read a sequence of images and log pixel values to file. When the unloadable count is nonzero, the extension is the next suspect; loading image files by content when the extension is wrong covers that diagnosis.
Should you keep UUID names or switch to a padded counter?
Keep the UUID names and drop the pattern, not the names: walking dataset/ with Path.rglob('*.png') and taking the person's name from the parent folder trains on any naming, while the counter plus zfill(5) only matches while a folder holds fewer than 100,000 images.
Both schemes earn their keep in different setups:
| uuid4 names | padded counter | |
|---|---|---|
| Two capture processes at once | no collisions | real risk: each restarts its own i at 0 and overwrites |
| Sort order equals capture order | no | yes |
| Human scanning the folder | poor | good |
| Works with a fixed-prefix glob | no | yes |
Pick the padded counter when order matters downstream: reproducible train/validation splits, a review tool that shows frame 00000 first, or scripts that already expect image_r_*.png. Pick UUIDs when several cameras or processes write into one folder. A compromise covers both — prefix with counter plus eight hex characters from uuid4's .hex, sortable and unique — and then anchor the loader regex to the new shape. How many stills to enroll per person, which sizes the counter, is worked out in face recognition enrollment from still images: what it takes.
How do you stop the next capture script from writing an unreadable dataset?
Make the capture loop prove its own output: one write function returns the path it saved, checks imwrite's return and raises on False, and the trainer reads a manifest of those paths instead of re-deriving names from a pattern.
- One writer function per project. It creates the folder with mkdir(parents=True, exist_ok=True), calls cv2.imwrite, checks the boolean and returns the Path. Every dataset file then has a verified write behind it.
- A manifest, not a glob. Append person and path to dataset/manifest.csv at each write, and let the trainer read that list. A rename or a pattern change can then never silently deselect files.
- A count at capture end. Print files written per person — 150 in the worked example — and compare with the manifest; a mismatch means the session died mid-write.
- The preflight before every training run. Refuse to train unless matched equals written and unloadable equals 0. Three lines of code turn a silent skip into a loud stop.
- Uniform crops at capture. Resize to 200 × 200 pixels and convert to grayscale before writing, so the loader never repairs pixel format later.
Where the dataset feeds a deployed recognizer rather than a one-off experiment, the full stage order is laid out in face recognition pipeline stages for an access-control camera build. More capture-and-storage debugging lives in the systems topic hub. If you are specifying the capture hardware itself, the camera finder filters smart cameras and depth cameras by interface, resolution and shutter, and the team will review a parts list with you through the contact page.
Questions
Does LBPH training need grayscale crops?
The OpenCV face module's LBPH train call expects single-channel images; color crops make it throw an error at training time. Load with cv2.IMREAD_GRAYSCALE, or convert with cv2.cvtColor before training. Resize every crop to one pixel size, such as 200 by 200, so the histograms the model stores stay consistent between people and between capture sessions.
How many images per person should I capture for LBPH training?
Plan on 50 crops per person as a workable floor and 150-300 for an enrollment that survives changes in pose, expression and lighting; the worked example uses 12 people at 150 crops each, 1,800 images total. Variety beats count: 300 near-identical frames teach the model less than 100 frames spread across angles, distances and light directions.
Why does cv2.imwrite return False instead of raising an error?
imwrite reports failure through its boolean return, not through exceptions: a missing parent folder, an extension that selects no encoder such as .txt, or a read-only folder all return False while the script keeps running. Check the return at the write site, because a silent False becomes imread's None and an empty training list one step later.
Do UUID filenames slow down LBPH training compared with sorted names?
No. Training time scales with image count and pixel count, not name order, and LBPH treats the training set as an unordered list of image-label pairs. Order matters only to your own tooling — reproducible train/validation splits, review folders that show frame 00000 first — and a padded counter or a manifest delivers that without renaming any file.