""" 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()