Rewrite README for the packaged pipeline

Cover the problem, the approach, how to run it and its measured
limitations, and correct what no longer matched the code (the --mode
flag, the .env file, the training directory). Update CLAUDE.md to the
new layout and commands.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-09 12:08:54 +01:00
co-authored by Claude Opus 5.5
parent 7b19d8f3e9
commit 36fae9cdc3
2 changed files with 133 additions and 107 deletions
+102 -75
View File
@@ -1,92 +1,119 @@
# Rowing Stats
Extract workout data from photos of Concept 2 PM5 rowing machine displays using computer vision and Claude's vision API.
Extract workout data from photos of Concept 2 PM5 rowing machine displays, using computer vision and Tesseract OCR, with Claude's vision API as a reference reader.
## How It Works
## The problem
Photos go through a three-stage pipeline:
After a session on the rowing machine I photograph the monitor. The time and distance on it are only useful for tracking progress once they are in a table, and typing them out from dozens of photos is tedious. This tool turns a folder of those photos into one row per workout.
The photos are handheld phone shots: the monitor is a small part of the frame, slightly rotated, lit differently each time, and surrounded by other bright rectangles (windows, walls, lockers). The camera roll also contains photos that are not of the monitor at all.
## The approach
```
photos/ → crop_to_screen.py → screen_classifier.py → extract_screen_data.py → rowing_results.csv
photos/ → crop → classify → ocr → results CSV
↘ claude (reference reader) ↗
```
1. **Screen Detection** (`crop_to_screen.py`) — Finds and perspective-corrects the LCD screen region using OpenCV edge detection, contour filtering, and morphological operations. Candidates are scored by `edge_density × area × rectangularity`.
2. **Classification** (`screen_classifier.py`) — Filters out non-rowing images. Supports a rule-based feature scorer (no training needed) and a 4-layer CNN with batch norm.
3. **Data Extraction** (`extract_screen_data.py`) — Extracts time and distance from cropped screen images using Tesseract OCR with multiple preprocessing variants (CLAHE, thresholding, scaling) and majority-vote extraction.
Each stage is a module under `src/rowing_stats/` and a subcommand of `rowing-stats`:
There is also `extract_rowing_data.py`, which uses Claude Haiku's vision API instead of Tesseract for data extraction. This serves as a reference/test for validating OCR accuracy but is more expensive to run due to API costs.
| Stage | Module | What it does |
|---|---|---|
| Screen detection | `crop.py` | Thresholds the photo at a sweep of brightness levels and keeps contours with the right size, aspect ratio and rectangularity. The LCD is told apart from other bright regions by its edge density (it is full of digits). Candidates are scored by `edge_density × area × rectangularity`, and the best one is perspective-corrected and saved. |
| Classification | `classifier.py` | Says whether a crop is a rowing display. Two modes: a rule-based scorer on hand-crafted features (contrast, edge density, saturation), and a 4-layer CNN trained on `train/`. |
| Extraction | `ocr.py`, `parsing.py` | Runs Tesseract over six preprocessed versions of each crop (two scales; CLAHE with fixed thresholds, Otsu, inverted Otsu). Every plausible time and distance in any of the six texts is a vote, and the majority wins. |
| Reference reader | `claude.py` | Sends the photo to Claude Haiku 4.5 and asks for the time and distance as JSON, then rejects readings outside sanity bounds. It costs an API call per photo, so it is used to produce the reference readings in `rowing_results.csv` that the OCR is scored against. |
| Tuning | `tune.py` | An Optuna search over the twelve screen detection parameters, maximising how many crops the CNN accepts as rowing displays. The defaults in `crop.CropParams` came from it. |
There is also an Optuna-based hyperparameter tuner (`optimize_crop.py`) for the screen detection parameters.
`results.py` holds the results table and its derived columns (pace, calories), `images.py` the image loading, and `errors.py` the exception types.
## Setup
### Dependencies
```
pip install anthropic torch torchvision opencv-python Pillow numpy optuna
```
### API Key
Create a `.env` file with your Anthropic API key:
```
ANTHROPIC_API_KEY=sk-ant-...
```
## Usage
### Full pipeline
```bash
# 1. Crop screens from photos
python crop_to_screen.py photos/ cropped/
# 2. Classify — keep only rowing displays
python screen_classifier.py predict --dir cropped/
# 3. Extract workout data via Tesseract OCR
python extract_screen_data.py --dir cropped/
# 3b. (Test) Extract via Claude API — more expensive, useful for validating OCR accuracy
python extract_rowing_data.py --dir photos/
```
### Individual commands
```bash
# Classify a single image (feature-based or CNN)
python screen_classifier.py predict --image path/to/img.jpg
python screen_classifier.py predict --image path/to/img.jpg --mode cnn
# Extract data from a single image (Tesseract OCR)
python extract_screen_data.py --image path/to/img.jpg
# Extract data from a single image (Claude API — for testing/validation)
python extract_rowing_data.py --image path/to/img.jpg
# Train the CNN classifier
python screen_classifier.py train --data-dir train/
# Optimize crop detection parameters
python optimize_crop.py --n-trials 300 --photos-dir photos/
```
## Training Data
The CNN classifier trains on labeled images in `train/`:
- `train/0/` — non-rowing images (negatives)
- `train/1/` — rowing display images (positives)
The trained model is saved as `screen_classifier_model.pth`.
## Validation
Extracted metrics are validated against sensible bounds:
The Claude reader's sanity bounds:
| Metric | Min | Max |
| -------- | --------- | --------- |
| Distance | 100 m | 100,000 m |
| Time | 30 s | 2 hrs |
| Pace | 1:20/500m | 2:30/500m |
## Running it
You need Python 3.10 or newer and, for the `ocr` command, the [Tesseract](https://tesseract-ocr.github.io/tessdoc/Installation.html) binary on your `PATH` (`apt install tesseract-ocr`, `brew install tesseract`, or `pacman -S tesseract tesseract-data-eng`).
```sh
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt # pinned: enough for crop, classify (features) and ocr
pip install -e .
```
Two commands need more, each with its own pinned file:
```sh
pip install -r requirements-claude.txt # the claude command; also set ANTHROPIC_API_KEY
pip install -r requirements-ml.txt # the CNN classifier and the tune command
```
### The pipeline
```sh
# 1. Crop screens from photos
rowing-stats crop photos/ cropped/
# 2. See which crops are rowing displays
rowing-stats classify predict --dir cropped/
rowing-stats classify predict --dir cropped/ --model cnn
# 3. Read time and distance with Tesseract, and score against the reference
rowing-stats ocr --dir cropped/ --output ocr_results.csv
rowing-stats ocr --dir cropped/ --validate rowing_results.csv
# Regenerate the reference with Claude (one paid API call per photo)
rowing-stats claude --dir photos/ --output rowing_results.csv
```
### Other commands
```sh
rowing-stats classify predict --image path/to/img.jpg # a single image
rowing-stats classify extract --image path/to/img.jpg # print its features
rowing-stats ocr --image path/to/crop.jpg
rowing-stats claude --image path/to/img.jpg
rowing-stats classify train --data-dir train/ # retrain the CNN
rowing-stats tune --n-trials 300 --photos-dir photos/ # search detection parameters
```
Every command reports a file it cannot process and carries on with the rest, and exits non-zero if any file failed. A problem that would affect every file (Tesseract not installed, no API key, missing model weights) stops the run with one message.
### Training data
The CNN trains on the labelled crops in `train/`: `train/0/` holds non-rowing images (81) and `train/1/` rowing displays (88, several crops per photo). The trained weights are committed as `screen_classifier_model.pth`.
### Tests
```sh
pip install -r requirements-dev.txt
pytest
```
The tests cover the vote-counting and parsing logic, the results table, the Claude reply parsing and sanity bounds, screen detection on synthetic photos, and each command's handling of unreadable images, missing tools and bad input. Tesseract and the Claude API are faked, so no test needs a key or makes a paid call; one test runs real Tesseract on a committed crop and is skipped if it is not installed. Tests that need torch or optuna are skipped when those are absent.
## Limitations
Measured on the 43 photos in `photos/`, against the 34 reference readings in `rowing_results.csv`, with Tesseract 5.5.3:
| Stage | Result |
|---|---|
| Screen detection | 41 of 43 photos produce a crop |
| OCR time | 31 of 34 correct (91%) |
| OCR distance | 20 of 34 correct (59%) |
- **The reference is itself a model's reading.** `rowing_results.csv` was produced by the Claude reader and has not been checked by hand, so "correct" means "agrees with Claude". Nine photos have no reference reading and are not scored.
- **The numbers are optimistic.** The detection parameters and the OCR preprocessing variants were chosen on these same photos. There is no held-out set.
- **Distance is unreliable.** The vote takes any 4–5 digit number on the screen as a candidate distance, and the display also shows calories per hour and projected distance, which can outvote the real one. Nothing ties a number to its position or its label. A distance read with a stray leading zero (`07337`) is also counted separately from the same number without it.
- **OCR output is not sanity-checked.** The pace bounds applied to Claude's readings are not applied to Tesseract's, so an implausible pairing such as 30:06 and 1,224 m is written out as read.
- **Only time and distance are read.** Stroke rate, split and calories on the display are ignored; the calories column is an estimate from distance.
- **The rule-based classifier does not reject much.** It accepts 86 of the 88 rowing crops in `train/1/` but also 70 of the 81 non-rowing images in `train/0/`. The CNN gets 88 of 88 and 80 of 81, but those are the images it was trained on.
- **The stages are not joined up.** Classification only prints labels; it does not filter what `ocr` reads, and there is no single command that takes a photo to a row.
- **Workout lengths are assumed.** Times under 10 minutes or over 2 hours, and distances under 1,000 m or over 50,000 m, are never read by the OCR path.
- **The photo date comes from the EXIF `DateTime` tag**, with no timezone, and only the Claude path records it (the crops carry no EXIF).
- **Screen detection assumes a lit, light-background LCD** that fills between about 0.4% and 14% of the frame.