Restructure prototype into the rowing_stats package
Split the script into one module per pipeline stage (image_io, display, ocr, parsing, pipeline, cli), with type hints throughout, and add packaging metadata and pinned dependencies. Failures are now typed exceptions instead of None returns and prints: unreadable, corrupt or missing images raise ImageLoadError, a photo with no detectable display raises DisplayNotFoundError, and a missing Tesseract binary raises TesseractNotInstalledError. The CLI reports a bad file and carries on, and exits non-zero if any file failed. It also gains JSON and CSV output. Behaviour changes: - OCR runs in sparse-text mode (--psm 11) without a character whitelist. The previous single-word mode (--psm 8) parsed no fields from any of the sample photos, and the whitelist made Tesseract drop the spaces the parser relies on to separate fields. - A 'Cal/hr' reading is no longer also reported as total calories. - The '500m' in a '/500m' pace label is no longer reported as distance. - A pace is no longer reported as elapsed time. - The distance is no longer also reported as projected distance. - Debug contour images are actually written (the float boxes were rejected by drawContours and the error swallowed). The unused matplotlib/imshow display helpers are dropped; plotting lives in the walkthrough notebook, which replaces the scratch one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
File diff suppressed because one or more lines are too long
-271
@@ -1,271 +0,0 @@
|
||||
"""
|
||||
Extract rowing stats from Concept2 PM5 monitor photos using OpenCV + Tesseract OCR.
|
||||
|
||||
Usage:
|
||||
python extract_data.py # process all photos/*.JPEG
|
||||
python extract_data.py photos/IMG_5485.JPEG photos/IMG_5550.JPEG
|
||||
python extract_data.py --debug ... # save intermediate images
|
||||
"""
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
import pytesseract as tess
|
||||
from PIL import Image
|
||||
from datetime import datetime
|
||||
|
||||
from matplotlib.figure import Figure
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
|
||||
# ── image loading ────────────────────────────────────────────────────────────
|
||||
|
||||
def load_pil(path: Path) -> Image.Image:
|
||||
return Image.open(path)
|
||||
|
||||
def pil_to_cv(img: Image.Image) -> np.ndarray:
|
||||
return cv.cvtColor(np.array(img), cv.COLOR_RGB2BGR)
|
||||
|
||||
def get_datetime_taken(img: Image.Image) -> datetime | None:
|
||||
exif = img.getexif()
|
||||
if 306 in exif:
|
||||
return datetime.strptime(exif[306], "%Y:%m:%d %H:%M:%S")
|
||||
return None
|
||||
|
||||
# ── image printing ────────────────────────────────────────────────────────────
|
||||
|
||||
def save_cv(fig: np.ndarray, path: Path) -> None:
|
||||
cv.imwrite(path, fig)
|
||||
|
||||
def show_cv(fig: np.ndarray) -> None:
|
||||
cv.imshow("fig", fig)
|
||||
cv.waitKey(0)
|
||||
cv.destroyAllWindows()
|
||||
|
||||
def cv_to_figure(fig: np.ndarray) -> Figure:
|
||||
img_rgb = cv.cvtColor(fig, cv.COLOR_BGR2RGB)
|
||||
matplotlib_fig = plt.figure()
|
||||
plt.imshow(img_rgb)
|
||||
plt.axis('off')
|
||||
return matplotlib_fig
|
||||
|
||||
def fig_to_cv(fig: Figure) -> np.ndarray:
|
||||
fig.canvas.draw()
|
||||
|
||||
# Get image from canvas
|
||||
image_from_plot = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
|
||||
image_from_plot = image_from_plot.reshape(fig.canvas.get_width_height()[::-1] + (3,))
|
||||
|
||||
# Convert RGB to BGR for OpenCV
|
||||
img_bgr = cv.cvtColor(image_from_plot, cv.COLOR_RGB2BGR)
|
||||
|
||||
return img_bgr
|
||||
|
||||
def save_fig(fig: Figure, path: Path) -> None:
|
||||
"""Save matplotlib Figure to disk"""
|
||||
fig.savefig(str(path), bbox_inches='tight', dpi=100)
|
||||
|
||||
def show_fig(fig: Figure) -> None:
|
||||
plt.show()
|
||||
|
||||
# ── display region detection ─────────────────────────────────────────────────
|
||||
|
||||
def order_points(pts: np.ndarray) -> np.ndarray:
|
||||
pts = pts.reshape(4, 2)
|
||||
rect = np.zeros((4, 2), dtype="float32")
|
||||
s = pts.sum(axis=1)
|
||||
rect[0] = pts[np.argmin(s)] # top-left
|
||||
rect[2] = pts[np.argmax(s)] # bottom-right
|
||||
diff = np.diff(pts, axis=1)
|
||||
rect[1] = pts[np.argmin(diff)] # top-right
|
||||
rect[3] = pts[np.argmax(diff)] # bottom-left
|
||||
return rect
|
||||
|
||||
|
||||
def crop_display(arr: np.ndarray, debug_prefix: str | None = None) -> np.ndarray | None:
|
||||
"""
|
||||
Detect the square LCD display on the PM5 monitor, perspective-warp it to
|
||||
a 400×400 image, and return it. Returns None if not found.
|
||||
"""
|
||||
blur = cv.GaussianBlur(arr, (7, 7), 0)
|
||||
edges = cv.Canny(blur, 50, 100)
|
||||
contours, _ = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
img_area = arr.shape[0] * arr.shape[1]
|
||||
candidates = []
|
||||
for cnt in contours:
|
||||
rect = cv.minAreaRect(cnt)
|
||||
(_, (w, h), _) = rect
|
||||
if w == 0 or h == 0:
|
||||
continue
|
||||
box = cv.boxPoints(rect).reshape((-1, 1, 2))
|
||||
area = cv.contourArea(box)
|
||||
if area < 0.01 * img_area:
|
||||
continue
|
||||
aspect = w / h
|
||||
if 0.9 < aspect < 1.1: # roughly square
|
||||
candidates.append(box)
|
||||
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
if debug_prefix and candidates:
|
||||
dbg = arr.copy()
|
||||
try:
|
||||
cv.drawContours(dbg, candidates, -1, (0, 255, 0), 3)
|
||||
cv.imwrite(f"{debug_prefix}_contours.png", dbg)
|
||||
except cv.error:
|
||||
pass # Skip debug image if contours can't be drawn
|
||||
|
||||
best = max(candidates, key=cv.contourArea)
|
||||
rect = order_points(best)
|
||||
size = 400
|
||||
dst = np.array([[0, 0], [size - 1, 0], [size - 1, size - 1], [0, size - 1]],
|
||||
dtype="float32")
|
||||
mat = cv.getPerspectiveTransform(rect, dst)
|
||||
warped = cv.warpPerspective(arr, mat, (size, size))
|
||||
|
||||
if debug_prefix:
|
||||
cv.imwrite(f"{debug_prefix}_warped.png", warped)
|
||||
|
||||
return warped
|
||||
|
||||
|
||||
# ── OCR ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
def ocr_image(warped: np.ndarray, debug_prefix: str | None = None) -> str:
|
||||
gray = cv.cvtColor(warped, cv.COLOR_BGR2GRAY)
|
||||
|
||||
# Scale up 3× — Tesseract works better on larger text
|
||||
gray = cv.resize(gray, (gray.shape[1] * 3, gray.shape[0] * 3),
|
||||
interpolation=cv.INTER_CUBIC)
|
||||
|
||||
# Bilateral filter: smooths noise while preserving edges
|
||||
gray = cv.bilateralFilter(gray, 9, 75, 75)
|
||||
|
||||
# Contrast enhancement via histogram equalization
|
||||
gray = cv.equalizeHist(gray)
|
||||
|
||||
# Otsu threshold is clean and effective for LCD displays
|
||||
_, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
|
||||
|
||||
if debug_prefix:
|
||||
cv.imwrite(f"{debug_prefix}_ocr_input.png", thresh)
|
||||
|
||||
# PSM 8: treat image as single word (works well for LCD data)
|
||||
config = (
|
||||
"--psm 8 "
|
||||
"-c tessedit_char_whitelist="
|
||||
"0123456789:./abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
|
||||
)
|
||||
return tess.image_to_string(thresh, config=config)
|
||||
|
||||
|
||||
# ── parsing ───────────────────────────────────────────────────────────────────
|
||||
|
||||
def process_ocr_text(text: str) -> dict:
|
||||
"""Parse raw OCR output into structured stats."""
|
||||
result: dict = {}
|
||||
full = " ".join(text.strip().split()) # collapse whitespace
|
||||
|
||||
# Elapsed time – first H:MM:SS or MM:SS in the string
|
||||
m = re.search(r"\b(\d{1,2}:\d{2}(?::\d{2})?)\b", full)
|
||||
if m:
|
||||
result["elapsed_time"] = m.group(1)
|
||||
|
||||
# Stroke rate – 2-digit number near s/m or S/m
|
||||
m = re.search(r"\b(\d{2})\s*[sS][/\\]m", full)
|
||||
if m:
|
||||
result["stroke_rate_spm"] = int(m.group(1))
|
||||
|
||||
# Distance in metres
|
||||
m = re.search(r"\b(\d{3,5})\s*m\b", full, re.IGNORECASE)
|
||||
if m:
|
||||
result["distance_m"] = int(m.group(1))
|
||||
|
||||
# Split pace /500m (e.g. 2:03 or 2:00.5)
|
||||
m = re.search(r"\b(\d:\d{2}(?:\.\d)?)\s*/500", full)
|
||||
if m:
|
||||
result["split_500m"] = m.group(1)
|
||||
|
||||
# Average split /500m (labelled "ave")
|
||||
m = re.search(r"\b(\d:\d{2}(?:\.\d)?)\s*ave", full, re.IGNORECASE)
|
||||
if m:
|
||||
result["avg_split_500m"] = m.group(1)
|
||||
|
||||
# Cal/hr (e.g. 958 Cal/hr or 1229 Cal/hr)
|
||||
m = re.search(r"\b(\d{3,4})\s*[cC]al[/\\][hH]r", full)
|
||||
if m:
|
||||
result["cal_per_hr"] = int(m.group(1))
|
||||
|
||||
# Total calories
|
||||
m = re.search(r"\b(\d{2,4})\s*[cC]al\b", full)
|
||||
if m:
|
||||
result["calories"] = int(m.group(1))
|
||||
|
||||
# Projected metres – typically a 5-digit number at the end
|
||||
for match in re.finditer(r"\b(\d{5})\b", full):
|
||||
result["projected_m"] = int(match.group(1)) # keep last hit
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ── main ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def process_file(path: Path, debug: bool = False) -> dict | None:
|
||||
debug_prefix = f"debug/{path.stem}" if debug else None
|
||||
if debug:
|
||||
Path("debug").mkdir(exist_ok=True)
|
||||
|
||||
img = load_pil(path)
|
||||
arr = pil_to_cv(img)
|
||||
|
||||
warped = crop_display(arr, debug_prefix)
|
||||
if warped is None:
|
||||
print(f" [!] Could not detect display region")
|
||||
return None
|
||||
|
||||
text = ocr_image(warped, debug_prefix)
|
||||
stats = process_ocr_text(text)
|
||||
stats["file"] = path.name
|
||||
|
||||
dt = get_datetime_taken(img)
|
||||
if dt:
|
||||
stats["datetime"] = dt.isoformat()
|
||||
|
||||
return text, stats
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
debug = "--debug" in args
|
||||
args = [a for a in args if a != "--debug"]
|
||||
|
||||
if args:
|
||||
paths = [Path(a) for a in args]
|
||||
else:
|
||||
photos = Path("photos")
|
||||
paths = sorted(photos.glob("*.JPEG")) + sorted(photos.glob("*.jpg"))
|
||||
|
||||
for path in paths:
|
||||
print(f"\n{'='*60}")
|
||||
print(f"File: {path.name}")
|
||||
|
||||
result = process_file(path, debug=debug)
|
||||
if result is None:
|
||||
continue
|
||||
|
||||
text, stats = result
|
||||
print("Raw OCR output:")
|
||||
print(text)
|
||||
print("Parsed stats:")
|
||||
for k, v in stats.items():
|
||||
print(f" {k}: {v}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "dc4ef0c3",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# Pipeline walkthrough\n",
|
||||
"\n",
|
||||
"Step through the extraction pipeline on a single photo to see what each stage produces.\n",
|
||||
"Requires `pip install -e \".[notebook]\"` from the repository root."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "221851b3",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import math\n",
|
||||
"from pathlib import Path\n",
|
||||
"\n",
|
||||
"import cv2 as cv\n",
|
||||
"import matplotlib.pyplot as plt\n",
|
||||
"import numpy as np\n",
|
||||
"\n",
|
||||
"from rowing_stats.display import crop_display\n",
|
||||
"from rowing_stats.image_io import get_datetime_taken, load_image, pil_to_cv\n",
|
||||
"from rowing_stats.ocr import ocr_image, preprocess_for_ocr\n",
|
||||
"from rowing_stats.parsing import parse_stats"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "438ecbd5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def plot_images(imgs: list[np.ndarray]):\n",
|
||||
" \"\"\"\n",
|
||||
" Plot a list of images in a single matplotlib figure.\n",
|
||||
"\n",
|
||||
" Parameters\n",
|
||||
" ----------\n",
|
||||
" imgs : list[np.ndarray]\n",
|
||||
" List of images (H×W greyscale or H×W×3 BGR arrays).\n",
|
||||
" \"\"\"\n",
|
||||
" if not imgs:\n",
|
||||
" return\n",
|
||||
"\n",
|
||||
" n = len(imgs)\n",
|
||||
" cols = math.ceil(math.sqrt(n))\n",
|
||||
" rows = math.ceil(n / cols)\n",
|
||||
"\n",
|
||||
" fig, axes = plt.subplots(rows, cols, figsize=(cols * 5, rows * 5))\n",
|
||||
" axes = np.atleast_1d(axes).ravel()\n",
|
||||
"\n",
|
||||
" for ax, img in zip(axes, imgs):\n",
|
||||
" if img.ndim == 2:\n",
|
||||
" ax.imshow(img, cmap=\"gray\")\n",
|
||||
" else:\n",
|
||||
" ax.imshow(cv.cvtColor(img, cv.COLOR_BGR2RGB))\n",
|
||||
" ax.axis(\"off\")\n",
|
||||
"\n",
|
||||
" # Hide any unused subplots\n",
|
||||
" for ax in axes[len(imgs):]:\n",
|
||||
" ax.axis(\"off\")\n",
|
||||
"\n",
|
||||
" plt.tight_layout()\n",
|
||||
" plt.show()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "da8bada5",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"photos_path = Path(\"../photos\")\n",
|
||||
"img = load_image(photos_path / \"IMG_5413.JPEG\")\n",
|
||||
"arr = pil_to_cv(img)\n",
|
||||
"print(get_datetime_taken(img))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "cb01649f",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"warped = crop_display(arr)\n",
|
||||
"plot_images([arr, warped, preprocess_for_ocr(warped)])"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "5dd910f8",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"text = ocr_image(warped)\n",
|
||||
"print(text)\n",
|
||||
"parse_stats(text)"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "Python 3",
|
||||
"language": "python",
|
||||
"name": "python3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "rowing-stats"
|
||||
version = "0.1.0"
|
||||
description = "Extract rowing stats from photos of a Concept2 PM5 monitor using OpenCV and Tesseract OCR"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"numpy>=2.0",
|
||||
"opencv-python-headless>=4.10",
|
||||
"pillow>=10.0",
|
||||
"pytesseract>=0.3.10",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8.0"]
|
||||
notebook = ["ipykernel", "matplotlib"]
|
||||
|
||||
[project.scripts]
|
||||
rowing-stats = "rowing_stats.cli:main"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
pythonpath = ["src"]
|
||||
@@ -0,0 +1,2 @@
|
||||
-r requirements.txt
|
||||
pytest==9.1.0
|
||||
@@ -0,0 +1,6 @@
|
||||
# Exact versions the pipeline was developed and tested against (Python 3.14).
|
||||
# Also requires the Tesseract binary (tested with 5.5.3) — see README.
|
||||
numpy==2.5.2
|
||||
opencv-python-headless==5.0.0.93
|
||||
pillow==12.3.0
|
||||
pytesseract==0.3.13
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Extract rowing stats from photos of a Concept2 PM5 monitor."""
|
||||
|
||||
from rowing_stats.errors import (
|
||||
DisplayNotFoundError,
|
||||
ImageLoadError,
|
||||
OcrError,
|
||||
RowingStatsError,
|
||||
TesseractNotInstalledError,
|
||||
)
|
||||
from rowing_stats.parsing import WorkoutStats, clean_ocr_text, parse_stats
|
||||
from rowing_stats.pipeline import ExtractionResult, process_file
|
||||
|
||||
__version__ = "0.1.0"
|
||||
|
||||
__all__ = [
|
||||
"DisplayNotFoundError",
|
||||
"ExtractionResult",
|
||||
"ImageLoadError",
|
||||
"OcrError",
|
||||
"RowingStatsError",
|
||||
"TesseractNotInstalledError",
|
||||
"WorkoutStats",
|
||||
"clean_ocr_text",
|
||||
"parse_stats",
|
||||
"process_file",
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
import sys
|
||||
|
||||
from rowing_stats.cli import main
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
Extract rowing stats from Concept2 PM5 monitor photos using OpenCV + Tesseract OCR.
|
||||
|
||||
Usage:
|
||||
rowing-stats # process every image in photos/
|
||||
rowing-stats photos/IMG_5485.JPEG photos/IMG_5550.JPEG
|
||||
rowing-stats --format csv -o stats.csv photos/
|
||||
rowing-stats --debug-dir debug ... # save intermediate images
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import fields
|
||||
from pathlib import Path
|
||||
from typing import TextIO
|
||||
|
||||
from rowing_stats.errors import RowingStatsError, TesseractNotInstalledError
|
||||
from rowing_stats.ocr import DEFAULT_PSM
|
||||
from rowing_stats.parsing import WorkoutStats
|
||||
from rowing_stats.pipeline import ExtractionResult, process_file
|
||||
|
||||
logger = logging.getLogger("rowing_stats")
|
||||
|
||||
IMAGE_SUFFIXES = {".jpeg", ".jpg", ".png"}
|
||||
DEFAULT_PHOTOS_DIR = Path("photos")
|
||||
CSV_COLUMNS = ["file", "datetime", *(f.name for f in fields(WorkoutStats))]
|
||||
|
||||
|
||||
def collect_paths(inputs: Sequence[Path]) -> list[Path]:
|
||||
"""Expand directories into the image files they contain; keep files as given."""
|
||||
paths: list[Path] = []
|
||||
for item in inputs:
|
||||
if item.is_dir():
|
||||
paths.extend(sorted(p for p in item.iterdir()
|
||||
if p.suffix.lower() in IMAGE_SUFFIXES))
|
||||
else:
|
||||
paths.append(item)
|
||||
return paths
|
||||
|
||||
|
||||
def write_text(results: Sequence[ExtractionResult], out: TextIO) -> None:
|
||||
for result in results:
|
||||
out.write(f"\n{'=' * 60}\n")
|
||||
out.write(f"File: {result.file}\n")
|
||||
out.write("Raw OCR output:\n")
|
||||
out.write(f"{result.raw_text}\n")
|
||||
out.write("Parsed stats:\n")
|
||||
for k, v in result.to_dict().items():
|
||||
out.write(f" {k}: {v}\n")
|
||||
|
||||
|
||||
def write_json(results: Sequence[ExtractionResult], out: TextIO) -> None:
|
||||
json.dump([r.to_dict() for r in results], out, indent=2)
|
||||
out.write("\n")
|
||||
|
||||
|
||||
def write_csv(results: Sequence[ExtractionResult], out: TextIO) -> None:
|
||||
writer = csv.DictWriter(out, fieldnames=CSV_COLUMNS)
|
||||
writer.writeheader()
|
||||
writer.writerows(r.to_dict() for r in results)
|
||||
|
||||
|
||||
WRITERS = {"text": write_text, "json": write_json, "csv": write_csv}
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="rowing-stats",
|
||||
description="Extract rowing stats from photos of a Concept2 PM5 monitor.",
|
||||
)
|
||||
parser.add_argument("paths", nargs="*", type=Path,
|
||||
help=f"image files or directories (default: {DEFAULT_PHOTOS_DIR}/)")
|
||||
parser.add_argument("--format", choices=sorted(WRITERS), default="text",
|
||||
help="output format (default: text)")
|
||||
parser.add_argument("-o", "--output", type=Path,
|
||||
help="write results to this file instead of stdout")
|
||||
parser.add_argument("--debug-dir", type=Path,
|
||||
help="save intermediate images (contours, crop, OCR input) here")
|
||||
parser.add_argument("--psm", type=int, default=DEFAULT_PSM,
|
||||
help=f"Tesseract page segmentation mode (default: {DEFAULT_PSM})")
|
||||
parser.add_argument("-v", "--verbose", action="store_true",
|
||||
help="log each file as it is processed")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: Sequence[str] | None = None) -> int:
|
||||
"""Run the CLI. Returns 0 if every file was processed, 1 if any failed."""
|
||||
args = build_parser().parse_args(argv)
|
||||
logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
|
||||
format="%(levelname)s: %(message)s", stream=sys.stderr)
|
||||
|
||||
paths = collect_paths(args.paths or [DEFAULT_PHOTOS_DIR])
|
||||
if not paths:
|
||||
logger.error("no images found")
|
||||
return 1
|
||||
|
||||
results: list[ExtractionResult] = []
|
||||
failures = 0
|
||||
for path in paths:
|
||||
logger.info("processing %s", path)
|
||||
try:
|
||||
results.append(process_file(path, debug_dir=args.debug_dir, psm=args.psm))
|
||||
except TesseractNotInstalledError as exc:
|
||||
# Environment problem, not a bad photo — every other file would fail too
|
||||
logger.error("%s", exc)
|
||||
return 1
|
||||
except RowingStatsError as exc:
|
||||
logger.error("%s: %s", path.name, exc)
|
||||
failures += 1
|
||||
|
||||
writer = WRITERS[args.format]
|
||||
if args.output is not None:
|
||||
with args.output.open("w", newline="") as fh:
|
||||
writer(results, fh)
|
||||
else:
|
||||
writer(results, sys.stdout)
|
||||
|
||||
if failures:
|
||||
logger.warning("%d of %d files could not be processed", failures, len(paths))
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Locating the PM5's LCD in a photo and warping it to a flat square."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
|
||||
from rowing_stats.errors import DisplayNotFoundError
|
||||
|
||||
WARPED_SIZE = 400
|
||||
MIN_AREA_FRACTION = 0.01
|
||||
MIN_ASPECT = 0.9
|
||||
MAX_ASPECT = 1.1
|
||||
|
||||
|
||||
def order_points(pts: np.ndarray) -> np.ndarray:
|
||||
"""Order four corner points as top-left, top-right, bottom-right, bottom-left."""
|
||||
pts = pts.reshape(4, 2)
|
||||
rect = np.zeros((4, 2), dtype="float32")
|
||||
s = pts.sum(axis=1)
|
||||
rect[0] = pts[np.argmin(s)] # top-left
|
||||
rect[2] = pts[np.argmax(s)] # bottom-right
|
||||
diff = np.diff(pts, axis=1)
|
||||
rect[1] = pts[np.argmin(diff)] # top-right
|
||||
rect[3] = pts[np.argmax(diff)] # bottom-left
|
||||
return rect
|
||||
|
||||
|
||||
def find_display_candidates(arr: np.ndarray) -> list[np.ndarray]:
|
||||
"""Return the bounding boxes of every large, roughly square contour."""
|
||||
blur = cv.GaussianBlur(arr, (7, 7), 0)
|
||||
edges = cv.Canny(blur, 50, 100)
|
||||
contours, _ = cv.findContours(edges, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
img_area = arr.shape[0] * arr.shape[1]
|
||||
candidates = []
|
||||
for cnt in contours:
|
||||
rect = cv.minAreaRect(cnt)
|
||||
(_, (w, h), _) = rect
|
||||
if w == 0 or h == 0:
|
||||
continue
|
||||
box = cv.boxPoints(rect).reshape((-1, 1, 2))
|
||||
if cv.contourArea(box) < MIN_AREA_FRACTION * img_area:
|
||||
continue
|
||||
if MIN_ASPECT < w / h < MAX_ASPECT:
|
||||
candidates.append(box)
|
||||
return candidates
|
||||
|
||||
|
||||
def crop_display(arr: np.ndarray, debug_prefix: Path | None = None) -> np.ndarray:
|
||||
"""
|
||||
Detect the square LCD display on the PM5 monitor and perspective-warp it
|
||||
to a WARPED_SIZE×WARPED_SIZE image.
|
||||
|
||||
Raises DisplayNotFoundError if no square region is found. If debug_prefix
|
||||
is given, the candidate outlines and the warped crop are written next to it.
|
||||
"""
|
||||
candidates = find_display_candidates(arr)
|
||||
if not candidates:
|
||||
raise DisplayNotFoundError("could not detect display region")
|
||||
|
||||
if debug_prefix is not None:
|
||||
dbg = arr.copy()
|
||||
cv.drawContours(dbg, [c.astype(np.int32) for c in candidates], -1, (0, 255, 0), 3)
|
||||
cv.imwrite(f"{debug_prefix}_contours.png", dbg)
|
||||
|
||||
best = max(candidates, key=cv.contourArea)
|
||||
rect = order_points(best)
|
||||
last = WARPED_SIZE - 1
|
||||
dst = np.array([[0, 0], [last, 0], [last, last], [0, last]], dtype="float32")
|
||||
mat = cv.getPerspectiveTransform(rect, dst)
|
||||
warped = cv.warpPerspective(arr, mat, (WARPED_SIZE, WARPED_SIZE))
|
||||
|
||||
if debug_prefix is not None:
|
||||
cv.imwrite(f"{debug_prefix}_warped.png", warped)
|
||||
|
||||
return warped
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Exceptions raised by the extraction pipeline."""
|
||||
|
||||
|
||||
class RowingStatsError(Exception):
|
||||
"""Base class for every error this package raises on purpose."""
|
||||
|
||||
|
||||
class ImageLoadError(RowingStatsError):
|
||||
"""The file is missing, unreadable, or not a decodable image."""
|
||||
|
||||
|
||||
class DisplayNotFoundError(RowingStatsError):
|
||||
"""No LCD-shaped region could be located in the photo."""
|
||||
|
||||
|
||||
class OcrError(RowingStatsError):
|
||||
"""Tesseract failed while reading the image."""
|
||||
|
||||
|
||||
class TesseractNotInstalledError(OcrError):
|
||||
"""The tesseract binary is not installed or not on PATH."""
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Loading photos and reading their EXIF metadata."""
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from rowing_stats.errors import ImageLoadError
|
||||
|
||||
EXIF_DATETIME_TAG = 306
|
||||
EXIF_DATETIME_FORMAT = "%Y:%m:%d %H:%M:%S"
|
||||
|
||||
|
||||
def load_image(path: Path) -> Image.Image:
|
||||
"""Open and fully decode an image, raising ImageLoadError if that fails."""
|
||||
try:
|
||||
img = Image.open(path)
|
||||
img.load() # Image.open is lazy; force decoding so truncated files fail here
|
||||
except FileNotFoundError as exc:
|
||||
raise ImageLoadError("file not found") from exc
|
||||
except UnidentifiedImageError as exc:
|
||||
raise ImageLoadError("not a recognised image format") from exc
|
||||
except OSError as exc:
|
||||
raise ImageLoadError(f"could not read image ({exc})") from exc
|
||||
return img
|
||||
|
||||
|
||||
def pil_to_cv(img: Image.Image) -> np.ndarray:
|
||||
"""Convert a PIL image to an OpenCV BGR array."""
|
||||
return cv.cvtColor(np.array(img.convert("RGB")), cv.COLOR_RGB2BGR)
|
||||
|
||||
|
||||
def get_datetime_taken(img: Image.Image) -> datetime | None:
|
||||
"""Return the EXIF timestamp of a photo, or None if absent or malformed."""
|
||||
raw = img.getexif().get(EXIF_DATETIME_TAG)
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
try:
|
||||
return datetime.strptime(raw.strip(), EXIF_DATETIME_FORMAT)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Preparing the cropped display for Tesseract and running OCR on it."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import cv2 as cv
|
||||
import numpy as np
|
||||
import pytesseract as tess
|
||||
|
||||
from rowing_stats.errors import OcrError, TesseractNotInstalledError
|
||||
|
||||
UPSCALE = 3
|
||||
# PSM 11: sparse text — find as much text as possible in no particular order.
|
||||
# The display is a grid of unrelated numbers, not a paragraph or a single word.
|
||||
# No character whitelist: with one, Tesseract drops the spaces between fields
|
||||
# ("30:06 29" comes back as "30:0629") and the parser can no longer split them.
|
||||
DEFAULT_PSM = 11
|
||||
|
||||
|
||||
def preprocess_for_ocr(warped: np.ndarray) -> np.ndarray:
|
||||
"""Turn the warped BGR display crop into a binarised image for Tesseract."""
|
||||
gray = cv.cvtColor(warped, cv.COLOR_BGR2GRAY)
|
||||
|
||||
# Scale up — Tesseract works better on larger text
|
||||
gray = cv.resize(gray, (gray.shape[1] * UPSCALE, gray.shape[0] * UPSCALE),
|
||||
interpolation=cv.INTER_CUBIC)
|
||||
|
||||
# Bilateral filter: smooths noise while preserving edges
|
||||
gray = cv.bilateralFilter(gray, 9, 75, 75)
|
||||
|
||||
# Contrast enhancement via histogram equalization
|
||||
gray = cv.equalizeHist(gray)
|
||||
|
||||
# Otsu threshold is clean and effective for LCD displays
|
||||
_, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY + cv.THRESH_OTSU)
|
||||
return thresh
|
||||
|
||||
|
||||
def ocr_image(warped: np.ndarray, debug_prefix: Path | None = None,
|
||||
psm: int = DEFAULT_PSM) -> str:
|
||||
"""
|
||||
OCR the warped display crop and return Tesseract's raw text.
|
||||
|
||||
Raises TesseractNotInstalledError if the tesseract binary is missing, or
|
||||
OcrError if it exits with an error.
|
||||
"""
|
||||
thresh = preprocess_for_ocr(warped)
|
||||
|
||||
if debug_prefix is not None:
|
||||
cv.imwrite(f"{debug_prefix}_ocr_input.png", thresh)
|
||||
|
||||
try:
|
||||
return tess.image_to_string(thresh, config=f"--psm {psm}")
|
||||
except tess.TesseractNotFoundError as exc:
|
||||
raise TesseractNotInstalledError(
|
||||
"tesseract is not installed or not on PATH "
|
||||
"(see https://tesseract-ocr.github.io/tessdoc/Installation.html)"
|
||||
) from exc
|
||||
except tess.TesseractError as exc:
|
||||
raise OcrError(f"tesseract failed: {exc}") from exc
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Turning raw OCR text into structured workout stats."""
|
||||
|
||||
import re
|
||||
from dataclasses import asdict, dataclass
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WorkoutStats:
|
||||
"""Fields read off the PM5 display. Anything not recognised stays None."""
|
||||
|
||||
elapsed_time: str | None = None
|
||||
stroke_rate_spm: int | None = None
|
||||
distance_m: int | None = None
|
||||
split_500m: str | None = None
|
||||
avg_split_500m: str | None = None
|
||||
cal_per_hr: int | None = None
|
||||
calories: int | None = None
|
||||
projected_m: int | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, str | int]:
|
||||
"""Return only the fields that were found."""
|
||||
return {k: v for k, v in asdict(self).items() if v is not None}
|
||||
|
||||
|
||||
# A pace such as 2:03 or 2:00.5
|
||||
_PACE = r"\d:[0-5]\d(?:\.\d)?"
|
||||
|
||||
# Elapsed time – H:MM:SS or MM:SS, but not a pace (decimal, or labelled /500m or ave)
|
||||
_ELAPSED_RE = re.compile(
|
||||
r"\b(\d{1,2}:[0-5]\d(?::[0-5]\d)?)\b(?!\.\d)(?!\s*/\s*500)(?!\s*ave)",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# Stroke rate – 2-digit number near s/m or S/m
|
||||
_STROKE_RATE_RE = re.compile(r"\b(\d{2})\s*s[/\\]m", re.IGNORECASE)
|
||||
# Distance in metres – but not the "500m" of a "/500m" pace label
|
||||
_DISTANCE_RE = re.compile(r"(?<!/)(?<!/\s)\b(\d{3,5})\s*m\b", re.IGNORECASE)
|
||||
_SPLIT_RE = re.compile(rf"\b({_PACE})\s*/\s*500")
|
||||
_AVG_SPLIT_RE = re.compile(rf"\b({_PACE})\s*ave", re.IGNORECASE)
|
||||
# Cal/hr (e.g. 958 Cal/hr or 1229 Cal/hr)
|
||||
_CAL_PER_HR_RE = re.compile(r"\b(\d{3,4})\s*cal\s*[/\\]\s*hr", re.IGNORECASE)
|
||||
# Total calories – "Cal" not followed by "/hr"
|
||||
_CALORIES_RE = re.compile(r"\b(\d{2,4})\s*cal\b(?!\s*[/\\])", re.IGNORECASE)
|
||||
_PROJECTED_RE = re.compile(r"\b(\d{4,5})\s*projected", re.IGNORECASE)
|
||||
_FIVE_DIGIT_RE = re.compile(r"\b(\d{5})\b")
|
||||
|
||||
|
||||
def clean_ocr_text(text: str) -> str:
|
||||
"""Collapse all runs of whitespace (including newlines) to single spaces."""
|
||||
return " ".join(text.split())
|
||||
|
||||
|
||||
def parse_stats(text: str) -> WorkoutStats:
|
||||
"""Parse raw OCR output into structured stats."""
|
||||
full = clean_ocr_text(text)
|
||||
|
||||
elapsed = _ELAPSED_RE.search(full)
|
||||
stroke_rate = _STROKE_RATE_RE.search(full)
|
||||
distance = _DISTANCE_RE.search(full)
|
||||
split = _SPLIT_RE.search(full)
|
||||
avg_split = _AVG_SPLIT_RE.search(full)
|
||||
cal_per_hr = _CAL_PER_HR_RE.search(full)
|
||||
calories = _CALORIES_RE.search(full)
|
||||
|
||||
return WorkoutStats(
|
||||
elapsed_time=elapsed.group(1) if elapsed else None,
|
||||
stroke_rate_spm=int(stroke_rate.group(1)) if stroke_rate else None,
|
||||
distance_m=int(distance.group(1)) if distance else None,
|
||||
split_500m=split.group(1) if split else None,
|
||||
avg_split_500m=avg_split.group(1) if avg_split else None,
|
||||
cal_per_hr=int(cal_per_hr.group(1)) if cal_per_hr else None,
|
||||
calories=int(calories.group(1)) if calories else None,
|
||||
projected_m=_parse_projected(full, distance),
|
||||
)
|
||||
|
||||
|
||||
def _parse_projected(full: str, distance: re.Match[str] | None) -> int | None:
|
||||
"""
|
||||
Projected metres: the number labelled "projected", else the last unlabelled
|
||||
5-digit number that is not the one already claimed as the distance.
|
||||
"""
|
||||
labelled = _PROJECTED_RE.search(full)
|
||||
if labelled:
|
||||
return int(labelled.group(1))
|
||||
|
||||
distance_span = distance.span(1) if distance else None
|
||||
unlabelled = [m for m in _FIVE_DIGIT_RE.finditer(full) if m.span(1) != distance_span]
|
||||
return int(unlabelled[-1].group(1)) if unlabelled else None
|
||||
@@ -0,0 +1,52 @@
|
||||
"""End-to-end extraction for a single photo."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from rowing_stats.display import crop_display
|
||||
from rowing_stats.image_io import get_datetime_taken, load_image, pil_to_cv
|
||||
from rowing_stats.ocr import DEFAULT_PSM, ocr_image
|
||||
from rowing_stats.parsing import WorkoutStats, parse_stats
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ExtractionResult:
|
||||
file: str
|
||||
taken_at: datetime | None
|
||||
raw_text: str
|
||||
stats: WorkoutStats
|
||||
|
||||
def to_dict(self) -> dict[str, str | int]:
|
||||
"""Flatten to a JSON-serialisable dict, omitting fields that were not found."""
|
||||
out: dict[str, str | int] = {"file": self.file}
|
||||
if self.taken_at is not None:
|
||||
out["datetime"] = self.taken_at.isoformat()
|
||||
out.update(self.stats.to_dict())
|
||||
return out
|
||||
|
||||
|
||||
def process_file(path: Path, debug_dir: Path | None = None,
|
||||
psm: int = DEFAULT_PSM) -> ExtractionResult:
|
||||
"""
|
||||
Load a photo, locate the display, OCR it and parse the stats.
|
||||
|
||||
Raises a RowingStatsError subclass if the image cannot be read, no display
|
||||
is found, or OCR fails. If debug_dir is given, intermediate images are
|
||||
written there.
|
||||
"""
|
||||
debug_prefix = None
|
||||
if debug_dir is not None:
|
||||
debug_dir.mkdir(parents=True, exist_ok=True)
|
||||
debug_prefix = debug_dir / path.stem
|
||||
|
||||
img = load_image(path)
|
||||
warped = crop_display(pil_to_cv(img), debug_prefix)
|
||||
text = ocr_image(warped, debug_prefix, psm=psm)
|
||||
|
||||
return ExtractionResult(
|
||||
file=path.name,
|
||||
taken_at=get_datetime_taken(img),
|
||||
raw_text=text,
|
||||
stats=parse_stats(text),
|
||||
)
|
||||
Reference in New Issue
Block a user