Measure Your Pulse From a Phone Video

Build a Python tool that estimates a pulse-like signal from a phone face video.

Introduction

30 Second Summary

Phone cameras record more than the details you notice when you watch a clip. Tiny shifts in skin colour can hide inside ordinary footage.

In this project, you will use Claude Code with Python to turn a steady phone video into an educational remote photoplethysmography experiment. Use its output only as noisy evidence because it cannot diagnose a condition or guide an emergency decision or determine whether someone is alive.

What You'll Build

You will run one command to see your sampled facial patches become an experimental BPM estimate with evidence showing whether that estimate looks plausible.

By the end of this project, you'll have:

  • A face-region preview that shows exactly where the program sampled your forehead plus both cheeks plus the background.
  • A signal journey from noisy RGB traces to a filtered POS waveform with its strongest pulse-like spectral peak.
  • A cautious artifact report that compares the video estimate with your doubled wrist count. It also challenges the peak using background evidence plus available keyframe timing.
  • Secret Mission: Add a pulse-locked colour magnifier that makes the selected skin patches visibly redden and fade with the extracted signal.

Are there any prerequisites?

No prior coding experience is required because the project includes the complete setup. You need internet access plus a phone with a camera plus a stand plus a Mac or Windows computer plus one month of Claude Pro.

Before We Start

Before the hands-on work begins, this is your moment to commit to a local educational phone-video pulse experiment. You will also set a firm safety boundary around its noisy BPM estimate.

Set Up Claude Code and Python

Your pulse experiment depends on a compatible Python runtime. Nothing is installed yet, so the first job is to build a toolchain you can verify before any video or source-code files appear.

You'll use Claude Code as your terminal-based coding partner through a Claude Pro subscription. This step also creates an isolated project environment with the exact scientific packages used by the pulse reader.

In this step, get ready to:
  • Connect Claude Code to your Claude Pro subscription.
  • Install the required Python version.
  • Create the isolated project environment with all pinned packages.
Install Claude Code and sign in

Claude Code runs inside macOS Terminal or Windows PowerShell. It can create files and run commands in the current folder once you approve its requests.

Know the subscription cost

This starts a paid monthly subscription, so pause before confirming the purchase. Claude Pro costs $20 per month in the US.

Local currency and taxes can vary. Decline optional usage credits if you want to keep spending within the subscription.

  • Visit the Claude upgrade page.
  • Subscribe to Claude Pro for one month.
  • Decline optional usage credits.

A version check tells you whether Claude Code is already available. Use the terminal for your computer to run it.

macOS

  • Press Command-Space to open Spotlight.
  • Type Terminal.
  • Press Return to open Terminal.
  • Check whether Claude Code is installed by running this command:
claude --version

An installed version prints a version number. An unavailable command means you need the installer in the next tab group.

Windows

  • Press the Windows key to open Start.
  • Type PowerShell.
  • Open Windows PowerShell.
  • Check whether Claude Code is installed by running this command:
claude --version

An installed version prints a version number. An unavailable command means you need the installer in the next tab group.

✔️ Claude Code is installed

Claude Code is already available in your terminal.

  • Continue to the sign-in check below.

ⓧ Claude Code is unavailable

The native installer adds Claude Code to your computer. Choose the command for your operating system.

macOS

  • Install Claude Code by running this command in Terminal:
curl -fsSL https://claude.ai/install.sh | bash

The command downloads the official installer script. The script installs the Claude Code command-line tool.

Windows

  • Install Claude Code by running this command in Windows PowerShell:
irm https://claude.ai/install.ps1 | iex

The command downloads the official PowerShell installer. The installer adds the Claude Code command-line tool.

A new terminal session loads the newly installed command. Start a fresh session before checking the version again.

macOS

  • Close the current Terminal window.
  • Press Command-Space to open Spotlight.
  • Type Terminal.
  • Press Return to open a new Terminal window.

Windows

  • Close the current Windows PowerShell window.
  • Press the Windows key to open Start.
  • Type PowerShell.
  • Open Windows PowerShell.
  • Verify the Claude Code installation by running this command:
claude --version

You should see an installed version number. This confirms the new terminal can find Claude Code.

  • Start Claude Code by running this command:
claude

Claude Code starts an interactive session. Your browser presents the sign-in flow when authentication is required.

  • Complete the browser sign-in with the account that has Claude Pro.
  • Return to the Claude Code session in your terminal.
  • Confirm the subscription sign-in method by entering this command inside Claude Code:
/status

The status view should identify your subscription sign-in method. This confirms Claude Code is connected to the Claude Pro account you intend to use.

Having trouble with Claude Code?

  • Close the terminal after installation if the new command is still unavailable. A fresh terminal session reloads your command path.
  • Check that the browser sign-in uses the same account as your Claude Pro subscription.
  • Return to the interactive Claude Code session before entering the status command.

Still stuck? Help me verify my Claude Code installation and Claude Pro sign-in.

Install the required Python version

The project uses Python 3.13.17 because the pinned scientific packages provide compatible builds for this runtime. Check the version before starting an installer.

macOS

  • Check for the required Python installation by running this command in Terminal:
python3.13 --version

A compatible installation prints Python 3.13.17. A different result determines which outcome tab to use.

Windows

  • Check for the required Python installation by running this command in Windows PowerShell:
py -3.13 --version

A compatible installation prints Python 3.13.17. A different result determines which outcome tab to use.

✔️ I see the required version

Python 3.13.17 is ready for the project environment.

  • Continue to the project environment substep.

ⓧ I see a different version

A different Python release does not satisfy this project's exact runtime pin. Install Python 3.13.17 using the path for your computer.

macOS

  • Download the macOS installer from the official Python 3.13.17 release page.
  • Open the downloaded .pkg file.
  • Choose Continue.
  • Choose Agree.
  • Choose Install.
  • Open /Applications/Python 3.13/ in Finder.
  • Double-click Install Certificates.command.

The certificate step should print Successfully installed certifi followed by update complete.

Windows

  • Download the Windows installer (64-bit) from the official Python 3.13.17 release page.
  • Open the downloaded installer.
  • Select Add Python to PATH.
  • Choose Install Now.
  • Keep the standard interpreter components selected.
  • Keep the pip component selected.

The installer adds Python 3.13.17 to the Python launcher. It also prepares pip for the package installation later in this step.

ⓧ Python is unavailable

The required Python command is unavailable. Install Python 3.13.17 using the path for your computer.

macOS

  • Download the macOS installer from the official Python 3.13.17 release page.
  • Open the downloaded .pkg file.
  • Choose Continue.
  • Choose Agree.
  • Choose Install.
  • Open /Applications/Python 3.13/ in Finder.
  • Double-click Install Certificates.command.

The certificate step should print Successfully installed certifi followed by update complete.

Windows

  • Download the Windows installer (64-bit) from the official Python 3.13.17 release page.
  • Open the downloaded installer.
  • Select Add Python to PATH.
  • Choose Install Now.
  • Keep the standard interpreter components selected.
  • Keep the pip component selected.

The installer adds Python 3.13.17 to the Python launcher. It also prepares pip for the package installation later in this step.

The installer is complete once the required version responds in your terminal. Run the platform check again to confirm it.

macOS

  • Verify the Python installation by running this command in Terminal:
python3.13 --version

You should see Python 3.13.17.

Windows

  • Verify the Python installation by running this command in Windows PowerShell:
py -3.13 --version

You should see Python 3.13.17.

Still seeing the wrong Python version?

  • Use python3.13 on macOS so the command targets the installed Python 3.13 runtime.
  • Use py -3.13 in Windows PowerShell so the launcher selects Python 3.13.
  • Open a fresh terminal window after the installer finishes if the command remains unavailable.

Need a hand? Help me verify my Python 3.13.17 installation.

Create the project environment

A virtual environment keeps the pulse reader's packages inside its own .venv directory. This protects the rest of your computer from project-specific dependency changes.

The environment needs four pinned scientific packages. Each package handles one part of the video and signal workflow.

Why these exact packages?

  • OpenCV-Python 4.13.0.92 reads video frames and includes the Haar XML files needed for face detection.
  • NumPy 2.5.4 stores the colour traces and performs array calculations.
  • SciPy 1.18.1 filters the pulse signal and calculates its power spectrum.
  • Matplotlib 3.11.2 turns the traces and spectrum into image files.
  • OpenCV-Python 5.0.0.93 has a confirmed packaging bug that leaves its Haar cascade directory empty. The 4.13.0.92 pin keeps the detector files available.

Placing the project on your Desktop gives it a predictable location. The terminal must finish inside the new invisible-pulse directory.

macOS

  • Move to your Desktop and display its path by running these commands:
cd ~/Desktop
pwd

The printed path should end in Desktop. This confirms where the project folder will be created.

  • Create the invisible-pulse folder and move into it by running these commands:
mkdir invisible-pulse
cd invisible-pulse
pwd

The printed path should end in Desktop/invisible-pulse. Your Terminal session is now inside the empty project folder.

Windows

  • Move to your Desktop and display its path by running these commands:
Set-Location -Path "$HOME\Desktop"
Get-Location

The printed path should end in Desktop. This confirms where the project folder will be created.

  • Create the invisible-pulse folder and move into it by running these commands:
New-Item -ItemType Directory invisible-pulse
Set-Location invisible-pulse
Get-Location

The printed path should end in Desktop\invisible-pulse. Your Windows PowerShell session is now inside the empty project folder.

The package installer may stay busy for a few minutes while it downloads compiled wheels. A stream of progress lines means it is still working.

macOS

  • Create .venv and install the pinned packages by running these commands:
python3.13 -m venv .venv
.venv/bin/python -m pip install opencv-python==4.13.0.92 numpy==2.5.4 scipy==1.18.1 matplotlib==3.11.2

The first command creates the isolated Python environment. The second command uses that environment's Python executable to install the four exact package versions.

Windows

  • Create .venv and install the pinned packages by running these commands:
py -3.13 -m venv .venv
.\.venv\Scripts\python.exe -m pip install opencv-python==4.13.0.92 numpy==2.5.4 scipy==1.18.1 matplotlib==3.11.2

The first command creates the isolated Python environment. The second command uses that environment's Python executable to install the four exact package versions.

Seeing package installation problems?

  • Confirm your terminal path ends in invisible-pulse before running the environment commands.
  • Confirm the platform-specific Python version command still prints 3.13.17.
  • Check your internet connection if package downloads stop before pip returns to the prompt.

Still blocked? Help me troubleshoot my pinned package installation.

Before you run the final checks, which four package version numbers do you expect the Python import to print?

macOS

  • Verify Claude Code and the project packages by running these commands:
claude --version
.venv/bin/python -c "import cv2, numpy, scipy, matplotlib; print(cv2.__version__, numpy.__version__, scipy.__version__, matplotlib.__version__)"

The first line should print your installed Claude Code version. The package check should print 4.13.0 2.5.4 1.18.1 3.11.2.

Windows

  • Verify Claude Code and the project packages by running these commands:
claude --version
.\.venv\Scripts\python.exe -c "import cv2, numpy, scipy, matplotlib; print(cv2.__version__, numpy.__version__, scipy.__version__, matplotlib.__version__)"

The first line should print your installed Claude Code version. The package check should print 4.13.0 2.5.4 1.18.1 3.11.2.

That's the setup complete: Claude Code can run from your terminal, Python imports every scientific package, and the project is ready without any video or source-code files yet.

✔️ Awesome, I've got everything!

Your terminal is inside invisible-pulse. Keep this terminal available for the next step.

ⓧ I'd like to double check the full code

This step creates no application code. Double-check the project environment artifact with the command for your computer.

macOS

  • Recheck the installed package versions by running this command inside invisible-pulse.
.venv/bin/python -c "import cv2, numpy, scipy, matplotlib; print(cv2.__version__, numpy.__version__, scipy.__version__, matplotlib.__version__)"

You should see 4.13.0 2.5.4 1.18.1 3.11.2.

Windows

  • Recheck the installed package versions by running this command inside invisible-pulse.
.\.venv\Scripts\python.exe -c "import cv2, numpy, scipy, matplotlib; print(cv2.__version__, numpy.__version__, scipy.__version__, matplotlib.__version__)"

You should see 4.13.0 2.5.4 1.18.1 3.11.2.

  • The invisible-pulse/.venv directory is a Python 3.13 virtual environment.
  • The environment contains OpenCV-Python 4.13.0.92, NumPy 2.5.4, SciPy 1.18.1, and Matplotlib 3.11.2.
  • The project contains no video or source-code files yet.

Your verified toolchain is ready for real input. Next up, you'll record the face video and produce the first visible RGB traces from its pixels.

Capture the Hidden Signal

A phone camera records tiny colour changes that your eyes cannot separate from the rest of the image. Remote photoplethysmography uses those changing pixels as a contactless signal.

This first pass turns your recording into visible sampling regions plus raw colour traces. Claude Code builds the inspection program from a detailed specification.

In this step, get ready to:
  • Capture a steady face video under controlled lighting.
  • Use Claude Code to create the inspect-only pulse reader.
  • Inspect the selected facial regions plus the raw RGB traces.
Record a controlled face video

The program detects your face in the first frame. It keeps those sampling regions fixed throughout the recording.

  • Secure your phone on its stand.
  • Position the phone at eye level.
  • Light your face with steady diffuse light from the front.
  • Choose a location without windows or flickering displays.
  • Select approximately 30 fps if your camera app offers that setting.
  • Center your face in the camera frame.

Why Keep the Camera Still?

Fixed regions let the program sample the same forehead plus cheek areas in every frame. Stable framing limits colour changes caused by the patches sliding across your face.

  • Look toward the camera.
  • Start the recording.
  • Remain as still as comfortable.
  • Breathe normally throughout the recording.
  • Stop the recording after about 40 seconds.

Your phone should now show a face video around 40 seconds long. Your face should remain centered throughout the clip.

Protect Your Recording

Your face video contains identifiable personal data. Keep the recording private on your computer.

Avoid a close-up palm recording for this project. Finger or handprint recordings can contain biometric information.

  • Transfer the recording to your computer using your usual cable or wireless transfer method.
  • Move the transferred recording into the existing invisible-pulse folder using Finder on macOS or File Explorer on Windows.
  • Rename the recording to face.mp4.
  • Confirm that face.mp4 appears beside the existing .venv folder.
Build the inspect-only program with Claude Code

A precise coding request gives Claude Code the boundaries for this first version. The program creates two inspection images without estimating BPM.

  • Start Claude Code from the current invisible-pulse folder by running this command:
claude

What Does This Command Do?

The claude command starts Claude Code in the current project folder. Its file operations stay focused on invisible-pulse when you give it the project boundary below.

You should see the Claude Code prompt using the subscription sign-in established in the previous step.

  • Paste this request into Claude Code:
Work only in this current project folder. Build the first, inspect-only version of a beginner-friendly Python command-line program named pulse_reader.py. Also create requirements.txt with these exact pins: opencv-python==4.13.0.92, numpy==2.5.4, scipy==1.18.1, matplotlib==3.11.2.

The script must accept a video path and an --inspect flag. Use OpenCV's packaged haarcascade_frontalface_default.xml to detect the largest face in the first frame. Keep that face box fixed because the recording is intentionally still. Define one forehead patch and two cheek patches as proportions of that face box, plus a corner background patch farthest from the face. Draw the face in yellow, skin patches in green, and background in blue, then save outputs/roi_preview.jpg.

Read the complete video. For every frame, spatially average BGR pixels from the three skin patches, convert that mean to RGB order, and save the channel traces. Use CAP_PROP_POS_MSEC when it advances and fall back to frame index divided by FPS otherwise. Resample all traces onto a uniform FPS time grid with numpy.interp. Plot each channel as percentage change from its own temporal mean and save outputs/raw_rgb.png.

For now, --inspect should stop after those two outputs. Use argparse and pathlib. Add clear errors for a missing video, an unreadable video, a missing cascade, no face in the first frame, or a recording shorter than 10 seconds. Do not add BPM estimation yet. After writing the files, show me a short summary and the exact Mac and Windows commands to run the inspection. Review your own code for unused imports before stopping.

What Will Claude Code Build?

  • The OpenCV face detector finds the largest face in the first frame.
  • Fixed facial regions of interest select the forehead plus both cheeks.
  • A corner background region records colour changes outside the selected skin.
  • NumPy resamples frame measurements onto a uniform time grid.
  • Matplotlib plots each channel as a percentage change from its temporal mean.
  • The --inspect flag stops the program after it creates the preview plus raw trace.

Claude Code may request permission before it writes files or runs commands. This is the point where careful review keeps the generated program aligned with the specification.

  • Review each proposed file write before approving it.
  • Confirm that requirements.txt contains the four requested package pins.
  • Confirm that pulse_reader.py contains the requested inspection functions.
  • Check that the proposed program does not estimate BPM.
  • Review each requested command before approving it.

✔️ Awesome, I've got everything!

Claude Code has created the inspect-only program plus its pinned requirements file. Keep both files in the current invisible-pulse folder.

ⓧ I'd like to double check the full code

Compare Claude Code's generated files with these complete inspect-only versions.

opencv-python==4.13.0.92
numpy==2.5.4
scipy==1.18.1
matplotlib==3.11.2
import argparse
from pathlib import Path

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np

CASCADE_NAME = "haarcascade_frontalface_default.xml"


def build_parser():
    parser = argparse.ArgumentParser(
        description="Educational phone-video pulse experiment. Not a medical device."
    )
    parser.add_argument("video", type=Path, help="Path to a face video")
    parser.add_argument(
        "--inspect",
        action="store_true",
        help="Only create the ROI preview and raw RGB plot",
    )
    return parser


def scaled_rect(face, x_start, y_start, x_end, y_end, frame_width, frame_height):
    x, y, width, height = [int(value) for value in face]
    x1 = max(0, x + int(width * x_start))
    y1 = max(0, y + int(height * y_start))
    x2 = min(frame_width, x + int(width * x_end))
    y2 = min(frame_height, y + int(height * y_end))
    if x2 <= x1 or y2 <= y1:
        raise ValueError("A calculated face patch is empty.")
    return x1, y1, x2, y2


def choose_background(face, frame_width, frame_height):
    patch_width = max(20, int(frame_width * 0.18))
    patch_height = max(20, int(frame_height * 0.18))
    candidates = [
        (0, 0, patch_width, patch_height),
        (frame_width - patch_width, 0, frame_width, patch_height),
        (0, frame_height - patch_height, patch_width, frame_height),
        (
            frame_width - patch_width,
            frame_height - patch_height,
            frame_width,
            frame_height,
        ),
    ]
    x, y, width, height = [int(value) for value in face]
    face_center = (x + width / 2.0, y + height / 2.0)

    def distance_squared(rect):
        x1, y1, x2, y2 = rect
        center = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
        return (center[0] - face_center[0]) ** 2 + (center[1] - face_center[1]) ** 2

    return max(candidates, key=distance_squared)


def detect_regions(first_frame):
    frame_height, frame_width = first_frame.shape[:2]
    cascade_path = cv.data.haarcascades + CASCADE_NAME
    cascade = cv.CascadeClassifier(cascade_path)
    if cascade.empty():
        raise RuntimeError(f"Could not load face cascade: {cascade_path}")

    gray = cv.cvtColor(first_frame, cv.COLOR_BGR2GRAY)
    gray = cv.equalizeHist(gray)
    minimum = max(60, min(frame_width, frame_height) // 10)
    faces = cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(minimum, minimum),
    )
    if len(faces) == 0:
        raise RuntimeError("No face was found in the first frame.")

    face = max(faces, key=lambda rect: int(rect[2]) * int(rect[3]))
    skin_regions = [
        scaled_rect(face, 0.30, 0.12, 0.70, 0.30, frame_width, frame_height),
        scaled_rect(face, 0.15, 0.52, 0.38, 0.74, frame_width, frame_height),
        scaled_rect(face, 0.62, 0.52, 0.85, 0.74, frame_width, frame_height),
    ]
    background_region = choose_background(face, frame_width, frame_height)
    return tuple(int(value) for value in face), skin_regions, background_region


def mean_bgr(frame, regions):
    pixel_groups = []
    for x1, y1, x2, y2 in regions:
        pixel_groups.append(frame[y1:y2, x1:x2].reshape(-1, 3))
    pixels = np.concatenate(pixel_groups, axis=0)
    return np.mean(pixels, axis=0)


def save_preview(frame, face, skin_regions, background_region, output_path):
    preview = frame.copy()
    x, y, width, height = face
    cv.rectangle(preview, (x, y), (x + width, y + height), (0, 255, 255), 3)
    for x1, y1, x2, y2 in skin_regions:
        cv.rectangle(preview, (x1, y1), (x2, y2), (0, 255, 0), 3)
    x1, y1, x2, y2 = background_region
    cv.rectangle(preview, (x1, y1), (x2, y2), (255, 0, 0), 3)
    if not cv.imwrite(str(output_path), preview):
        raise RuntimeError(f"Could not write {output_path}")


def extract_video(video_path, output_dir):
    if not video_path.is_file():
        raise FileNotFoundError(f"Video not found: {video_path}")

    capture = cv.VideoCapture(str(video_path))
    if not capture.isOpened():
        raise RuntimeError(f"Could not open video: {video_path}")
    capture.set(cv.CAP_PROP_ORIENTATION_AUTO, 1)

    fps = float(capture.get(cv.CAP_PROP_FPS))
    if fps <= 0:
        capture.release()
        raise RuntimeError("The video backend did not report a usable FPS.")

    ok, frame = capture.read()
    if not ok:
        capture.release()
        raise RuntimeError("The video has no readable frames.")

    frame_height, frame_width = frame.shape[:2]
    face, skin_regions, background_region = detect_regions(frame)
    save_preview(
        frame,
        face,
        skin_regions,
        background_region,
        output_dir / "roi_preview.jpg",
    )

    times = []
    skin_rgb = []
    background_green = []
    frame_index = 0

    while ok:
        timestamp = float(capture.get(cv.CAP_PROP_POS_MSEC)) / 1000.0
        if times and timestamp <= times[-1]:
            timestamp = times[-1] + 1.0 / fps
        elif not times and timestamp < 0:
            timestamp = 0.0

        skin_mean = mean_bgr(frame, skin_regions)
        background_mean = mean_bgr(frame, [background_region])
        skin_rgb.append(skin_mean[::-1])
        background_green.append(float(background_mean[1]))
        times.append(timestamp)

        frame_index += 1
        ok, frame = capture.read()

    capture.release()

    if frame_index < max(64, int(10 * fps)):
        raise RuntimeError("Record at least 10 seconds of usable video.")

    source_times = np.asarray(times, dtype=float)
    source_times = source_times - source_times[0]
    if source_times[-1] <= 0:
        source_times = np.arange(frame_index, dtype=float) / fps

    uniform_times = np.arange(
        0.0,
        source_times[-1] + 0.5 / fps,
        1.0 / fps,
        dtype=float,
    )
    skin_rgb_array = np.asarray(skin_rgb, dtype=float)
    uniform_rgb = np.column_stack(
        [
            np.interp(uniform_times, source_times, skin_rgb_array[:, channel])
            for channel in range(3)
        ]
    )
    uniform_background = np.interp(
        uniform_times,
        source_times,
        np.asarray(background_green, dtype=float),
    )

    return {
        "times": uniform_times,
        "rgb": uniform_rgb,
        "background_green": uniform_background,
        "fps": fps,
        "face": face,
        "skin_regions": skin_regions,
        "background_region": background_region,
        "width": frame_width,
        "height": frame_height,
    }


def save_raw_rgb_plot(times, rgb, output_path):
    channel_mean = np.mean(rgb, axis=0)
    relative = 100.0 * (rgb / channel_mean - 1.0)
    figure, axis = plt.subplots(figsize=(10, 4))
    axis.plot(times, relative[:, 0], color="red", label="Red")
    axis.plot(times, relative[:, 1], color="green", label="Green")
    axis.plot(times, relative[:, 2], color="blue", label="Blue")
    axis.set_title("Raw skin-patch RGB change")
    axis.set_xlabel("Time (seconds)")
    axis.set_ylabel("Change from channel mean (%)")
    axis.legend()
    figure.tight_layout()
    figure.savefig(output_path, dpi=150)
    plt.close(figure)


def analyze_video(video_path, output_dir, wrist_count=None, inspect_only=False):
    output_dir.mkdir(parents=True, exist_ok=True)
    data = extract_video(video_path, output_dir)
    save_raw_rgb_plot(data["times"], data["rgb"], output_dir / "raw_rgb.png")

    if inspect_only:
        print(f"Saved {output_dir / 'roi_preview.jpg'}")
        print(f"Saved {output_dir / 'raw_rgb.png'}")
        return data


def main():
    args = build_parser().parse_args()
    analyze_video(
        args.video,
        Path("outputs"),
        inspect_only=args.inspect,
    )


if __name__ == "__main__":
    main()

Missing One of the Files?

  • Ask Claude Code to compare its generated files with the complete versions in the double-check tab.
  • Check that requirements.txt contains one package pin per line.
  • Check that pulse_reader.py ends with the call to main().

Still stuck? Help me compare the generated inspection files with the required versions.

Run and inspect the first pass

Inspection mode converts the recording into two visible checkpoints. The preview verifies the sampled pixels before the raw plot exposes their colour changes.

Before the inspection, here is your prediction question: will the three colour traces follow one clean pattern.

  • Return to your normal terminal prompt after Claude Code finishes.
  • Run the inspection with the Python interpreter inside the existing virtual environment:

macOS

.venv/bin/python pulse_reader.py face.mp4 --inspect

What Does This Command Do?

The virtual environment runs pulse_reader.py against face.mp4. Inspection mode creates the region preview plus the raw RGB plot.

You should see confirmation that outputs/roi_preview.jpg plus outputs/raw_rgb.png were saved.

Windows

.\.venv\Scripts\python.exe pulse_reader.py face.mp4 --inspect

What Does This Command Do?

The virtual environment runs pulse_reader.py against face.mp4. Inspection mode creates the region preview plus the raw RGB plot.

You should see confirmation that outputs/roi_preview.jpg plus outputs/raw_rgb.png were saved.

Inspection Did Not Finish?

  • Confirm that face.mp4 is inside the current invisible-pulse folder.
  • Check that the inspection command includes --inspect.
  • Use a recording whose first frame shows your centered face clearly.
  • Use a recording with at least 10 seconds of readable video.

Need help? Help me diagnose why the inspection did not create both output images.

  • Return to the existing invisible-pulse folder in Finder on macOS or File Explorer on Windows.
  • Open the new outputs folder.
  • Open roi_preview.jpg in your image viewer.
  • Check that one yellow rectangle surrounds your face.
  • Check that three green rectangles cover only your forehead plus cheeks.
  • Check that one blue rectangle covers a far corner of the frame.

✔️ The patches cover the right areas

The region check is complete. Your program now samples skin without including hair, eyes, or the mouth.

  • Open raw_rgb.png from the same outputs folder.

ⓧ A patch covers the wrong area

A misplaced patch replaces skin colour with hair or eye movement. Correct the region before using its signal.

  • Return to the Claude Code session from earlier.
  • Describe which green patch covers hair, an eye, or the mouth.
  • Ask Claude Code to adjust only that patch's proportional coordinates.
  • Review the proposed coordinate change before accepting it.
  • Return to your normal terminal prompt.
  • Run the platform-specific inspection command again.
  • Reopen roi_preview.jpg to confirm the corrected placement.
  • Open raw_rgb.png after the region check passes.

You should see separate red, green, and blue traces that drift across the plot. The lines contain visible noise instead of one clean heartbeat pattern.

The Messy Trace Is the Lesson

Shared movement can shift all three channels. Automatic exposure can create slow changes that dominate the smaller pulse-related colour shifts.

This shortfall is intentional. The plot proves that the video contains measurable colour changes while showing why the raw channels need signal processing.

That is your first visible signal captured. Your program now turns an ordinary phone video into checked facial regions plus measurable RGB traces.

Your inspection pipeline works from video input to plotted colour traces. Next, the POS projection will isolate a more plausible pulse-like pattern from the shared variation.

Extract a Pulse Estimate

Your inspection pass proved that the camera captured changing RGB values from the selected skin patches. Those raw traces also exposed the drift and shared noise that make a direct pulse reading unreliable.

This step turns those traces into an experimental estimate with the Plane-Orthogonal-to-Skin algorithm. A narrow Butterworth filter then keeps frequencies between 0.7 and 3.0 Hz before a power spectrum identifies the strongest candidate.

In this step, get ready to:
  • Extend the inspection script with POS projection and temporal filtering.
  • Run the full analysis to calculate an experimental BPM estimate.
  • Inspect the filtered trace and marked spectral peak for signs of uncertainty.
Ask Claude Code to implement POS

The raw colour channels contain pulse information mixed with lighting and movement. POS normalizes the RGB channels before combining them into a pulse-like signal that suppresses some shared intensity changes.

Why POS for this signal?

A single green trace remains exposed to lighting shifts and small movements. POS uses relationships between normalized red, green, and blue values to reduce those shared changes.

The result is still an experimental signal. Filtering and spectral analysis help test whether it contains a plausible repeating component.

  • Switch back to the Claude Code session for the invisible-pulse folder.
  • Extend pulse_reader.py by pasting this prompt into Claude Code:
Extend pulse_reader.py without breaking --inspect. Implement the Plane-Orthogonal-to-Skin algorithm exactly from Wang et al.'s published core method. Use a sliding window of 1.6 seconds scaled to the video's FPS. In each window, transpose RGB into a 3 by window array, divide each channel by its temporal mean, calculate S1 = Gn - Bn and S2 = Gn + Bn - 2*Rn, calculate alpha = std(S1) / std(S2), then overlap-add h = S1 + alpha*S2 after removing h's mean. Protect only the zero-denominator case with a tiny positive constant.

Then design a third-order Butterworth band-pass with scipy.signal.butter using [0.7, 3.0] Hz, the video's FPS, btype='bandpass', and output='sos'. Apply scipy.signal.sosfiltfilt. Estimate the dominant frequency with scipy.signal.periodogram using window='hann' and scaling='density', search only 0.7 to 3.0 Hz, and convert the winning frequency to BPM by multiplying by 60.

Create outputs/pulse_analysis.png with the filtered time signal on top and the in-band power spectrum on the bottom. Plot the spectrum's horizontal axis in BPM and mark the selected BPM with axvline. Keep functions small and reusable because a later stretch file will import analyze_video. Update the command output to label the number Experimental video BPM and include a non-medical warning. Show me the code changes and exact Mac and Windows run commands.

What does this prompt add?

  • The 1.6-second sliding window adapts the RGB projection over short sections of the recording.
  • The POS equations combine normalized channels while reducing shared brightness changes.
  • The third-order band-pass keeps frequencies from 0.7 to 3.0 Hz. That range corresponds to 42 to 180 cycles per minute.
  • The Hann-window periodogram measures how signal power is distributed across frequencies. Its strongest in-band frequency becomes the experimental BPM candidate.

Claude Code may request permission to edit pulse_reader.py or run the program. This review is where you catch a changed equation before it becomes a convincing plot.

  • Review the proposed changes to pulse_reader.py.
  • Confirm that S1 subtracts normalized blue from normalized green.
  • Confirm that S2 subtracts twice the normalized red channel from normalized green plus normalized blue.
  • Confirm that the filter uses third-order second-order sections between 0.7 and 3.0 Hz.
  • Approve the file edit after those details match the prompt.

Claude Code should finish with a summary of the new functions and commands. Your inspection workflow remains available through --inspect.

Did the generated code drift?

  • Ask Claude Code to compare the projection signs against the prompt if either POS equation changed.
  • Ask Claude Code to preserve the existing inspection branch if it removed the early return for inspect_only.
  • Reject automatic frequency removal if Claude Code adds a notch filter or deletes a spectral peak.

Need help reviewing the diff? Help me check whether my POS projection and Butterworth filter match the project requirements.

Run the pulse analysis

The normal command now continues beyond inspection. It projects the RGB traces into a POS signal before filtering that signal and calculating its strongest in-band frequency.

Before you run the analysis, do you expect the filtered trace to keep the raw drift or settle into a more regular oscillation?

macOS

  • Run the full analysis with the project virtual environment by entering:
.venv/bin/python pulse_reader.py face.mp4

Windows

  • Run the full analysis with the project virtual environment by entering:
.\.venv\Scripts\python.exe pulse_reader.py face.mp4

What does this command do?

The command processes every frame from face.mp4 with the Python interpreter inside .venv. It then saves the filtered waveform and spectrum to outputs/pulse_analysis.png.

You should see a line beginning with Experimental video BPM in the terminal. You should also see confirmation that outputs/pulse_analysis.png was saved.

That is the core signal pipeline working. Your program now turns video pixels into a measurable pulse candidate while keeping the result clearly non-medical.

Did the analysis fail?

  • Confirm that the command uses the Python executable inside the existing .venv folder.
  • Check that face.mp4 remains directly inside the invisible-pulse folder.
  • Compare the generated filter limits with LOW_HZ and HIGH_HZ if the filtering stage reports a problem.

Still blocked? Help me diagnose why the full pulse analysis command fails while the inspect command works.

✔️ Awesome, I've got everything!

Great. Save pulse_reader.py and keep outputs/pulse_analysis.png available for the visual check.

ⓧ I'd like to double check the full code

Compare your cumulative pulse_reader.py with this pulse-analysis version:

import argparse
from pathlib import Path

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import butter, periodogram, sosfiltfilt

LOW_HZ = 0.7
HIGH_HZ = 3.0
CASCADE_NAME = "haarcascade_frontalface_default.xml"


def build_parser():
    parser = argparse.ArgumentParser(
        description="Educational phone-video pulse experiment. Not a medical device."
    )
    parser.add_argument("video", type=Path, help="Path to a face video")
    parser.add_argument(
        "--inspect",
        action="store_true",
        help="Only create the ROI preview and raw RGB plot",
    )
    return parser


def scaled_rect(face, x_start, y_start, x_end, y_end, frame_width, frame_height):
    x, y, width, height = [int(value) for value in face]
    x1 = max(0, x + int(width * x_start))
    y1 = max(0, y + int(height * y_start))
    x2 = min(frame_width, x + int(width * x_end))
    y2 = min(frame_height, y + int(height * y_end))
    if x2 <= x1 or y2 <= y1:
        raise ValueError("A calculated face patch is empty.")
    return x1, y1, x2, y2


def choose_background(face, frame_width, frame_height):
    patch_width = max(20, int(frame_width * 0.18))
    patch_height = max(20, int(frame_height * 0.18))
    candidates = [
        (0, 0, patch_width, patch_height),
        (frame_width - patch_width, 0, frame_width, patch_height),
        (0, frame_height - patch_height, patch_width, frame_height),
        (
            frame_width - patch_width,
            frame_height - patch_height,
            frame_width,
            frame_height,
        ),
    ]
    x, y, width, height = [int(value) for value in face]
    face_center = (x + width / 2.0, y + height / 2.0)

    def distance_squared(rect):
        x1, y1, x2, y2 = rect
        center = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
        return (center[0] - face_center[0]) ** 2 + (center[1] - face_center[1]) ** 2

    return max(candidates, key=distance_squared)


def detect_regions(first_frame):
    frame_height, frame_width = first_frame.shape[:2]
    cascade_path = cv.data.haarcascades + CASCADE_NAME
    cascade = cv.CascadeClassifier(cascade_path)
    if cascade.empty():
        raise RuntimeError(f"Could not load face cascade: {cascade_path}")

    gray = cv.cvtColor(first_frame, cv.COLOR_BGR2GRAY)
    gray = cv.equalizeHist(gray)
    minimum = max(60, min(frame_width, frame_height) // 10)
    faces = cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(minimum, minimum),
    )
    if len(faces) == 0:
        raise RuntimeError("No face was found in the first frame.")

    face = max(faces, key=lambda rect: int(rect[2]) * int(rect[3]))
    skin_regions = [
        scaled_rect(face, 0.30, 0.12, 0.70, 0.30, frame_width, frame_height),
        scaled_rect(face, 0.15, 0.52, 0.38, 0.74, frame_width, frame_height),
        scaled_rect(face, 0.62, 0.52, 0.85, 0.74, frame_width, frame_height),
    ]
    background_region = choose_background(face, frame_width, frame_height)
    return tuple(int(value) for value in face), skin_regions, background_region


def mean_bgr(frame, regions):
    pixel_groups = []
    for x1, y1, x2, y2 in regions:
        pixel_groups.append(frame[y1:y2, x1:x2].reshape(-1, 3))
    pixels = np.concatenate(pixel_groups, axis=0)
    return np.mean(pixels, axis=0)


def save_preview(frame, face, skin_regions, background_region, output_path):
    preview = frame.copy()
    x, y, width, height = face
    cv.rectangle(preview, (x, y), (x + width, y + height), (0, 255, 255), 3)
    for x1, y1, x2, y2 in skin_regions:
        cv.rectangle(preview, (x1, y1), (x2, y2), (0, 255, 0), 3)
    x1, y1, x2, y2 = background_region
    cv.rectangle(preview, (x1, y1), (x2, y2), (255, 0, 0), 3)
    if not cv.imwrite(str(output_path), preview):
        raise RuntimeError(f"Could not write {output_path}")


def extract_video(video_path, output_dir):
    if not video_path.is_file():
        raise FileNotFoundError(f"Video not found: {video_path}")

    capture = cv.VideoCapture(str(video_path))
    if not capture.isOpened():
        raise RuntimeError(f"Could not open video: {video_path}")
    capture.set(cv.CAP_PROP_ORIENTATION_AUTO, 1)

    fps = float(capture.get(cv.CAP_PROP_FPS))
    if fps <= 0:
        capture.release()
        raise RuntimeError("The video backend did not report a usable FPS.")

    ok, frame = capture.read()
    if not ok:
        capture.release()
        raise RuntimeError("The video has no readable frames.")

    frame_height, frame_width = frame.shape[:2]
    face, skin_regions, background_region = detect_regions(frame)
    save_preview(
        frame,
        face,
        skin_regions,
        background_region,
        output_dir / "roi_preview.jpg",
    )

    times = []
    skin_rgb = []
    background_green = []
    frame_index = 0

    while ok:
        timestamp = float(capture.get(cv.CAP_PROP_POS_MSEC)) / 1000.0
        if times and timestamp <= times[-1]:
            timestamp = times[-1] + 1.0 / fps
        elif not times and timestamp < 0:
            timestamp = 0.0

        skin_mean = mean_bgr(frame, skin_regions)
        background_mean = mean_bgr(frame, [background_region])
        skin_rgb.append(skin_mean[::-1])
        background_green.append(float(background_mean[1]))
        times.append(timestamp)

        frame_index += 1
        ok, frame = capture.read()

    capture.release()

    if frame_index < max(64, int(10 * fps)):
        raise RuntimeError("Record at least 10 seconds of usable video.")

    source_times = np.asarray(times, dtype=float)
    source_times = source_times - source_times[0]
    if source_times[-1] <= 0:
        source_times = np.arange(frame_index, dtype=float) / fps

    uniform_times = np.arange(
        0.0,
        source_times[-1] + 0.5 / fps,
        1.0 / fps,
        dtype=float,
    )
    skin_rgb_array = np.asarray(skin_rgb, dtype=float)
    uniform_rgb = np.column_stack(
        [
            np.interp(uniform_times, source_times, skin_rgb_array[:, channel])
            for channel in range(3)
        ]
    )
    uniform_background = np.interp(
        uniform_times,
        source_times,
        np.asarray(background_green, dtype=float),
    )

    return {
        "times": uniform_times,
        "rgb": uniform_rgb,
        "background_green": uniform_background,
        "fps": fps,
        "face": face,
        "skin_regions": skin_regions,
        "background_region": background_region,
        "width": frame_width,
        "height": frame_height,
    }


def save_raw_rgb_plot(times, rgb, output_path):
    channel_mean = np.mean(rgb, axis=0)
    relative = 100.0 * (rgb / channel_mean - 1.0)
    figure, axis = plt.subplots(figsize=(10, 4))
    axis.plot(times, relative[:, 0], color="red", label="Red")
    axis.plot(times, relative[:, 1], color="green", label="Green")
    axis.plot(times, relative[:, 2], color="blue", label="Blue")
    axis.set_title("Raw skin-patch RGB change")
    axis.set_xlabel("Time (seconds)")
    axis.set_ylabel("Change from channel mean (%)")
    axis.legend()
    figure.tight_layout()
    figure.savefig(output_path, dpi=150)
    plt.close(figure)


def pos_signal(rgb, fps):
    sample_count = len(rgb)
    pulse = np.zeros(sample_count, dtype=float)
    window_length = max(3, int(round(1.6 * fps)))
    if sample_count < window_length:
        raise ValueError("The recording is too short for the POS window.")

    for end in range(window_length - 1, sample_count):
        start = end - window_length + 1
        window = rgb[start : end + 1].T
        temporal_mean = np.mean(window, axis=1, keepdims=True)
        normalized = window / temporal_mean
        s1 = normalized[1] - normalized[2]
        s2 = normalized[1] + normalized[2] - 2.0 * normalized[0]
        denominator = float(np.std(s2))
        if denominator <= 1e-12:
            denominator = 1e-12
        alpha = float(np.std(s1)) / denominator
        segment = s1 + alpha * s2
        pulse[start : end + 1] += segment - np.mean(segment)

    return pulse


def bandpass(signal, fps):
    sos = butter(
        3,
        [LOW_HZ, HIGH_HZ],
        btype="bandpass",
        fs=fps,
        output="sos",
    )
    return sosfiltfilt(sos, signal)


def dominant_frequency(signal, fps):
    frequencies, power = periodogram(
        signal,
        fs=fps,
        window="hann",
        scaling="density",
    )
    band = (frequencies >= LOW_HZ) & (frequencies <= HIGH_HZ)
    band_frequencies = frequencies[band]
    band_power = power[band]
    if len(band_frequencies) == 0:
        raise RuntimeError("No spectrum bins landed inside the pulse band.")
    peak_index = int(np.argmax(band_power))
    total_power = float(sum(band_power))
    peak_share = 0.0 if total_power <= 0 else float(band_power[peak_index]) / total_power
    return (
        float(band_frequencies[peak_index]),
        peak_share,
        frequencies,
        power,
    )


def save_analysis_plot(
    times,
    filtered,
    skin_frequencies,
    skin_power,
    pulse_bpm,
    output_path,
):
    figure, axes = plt.subplots(2, 1, figsize=(10, 7))
    axes[0].plot(times, filtered, color="purple", label="Filtered POS")
    axes[0].set_title("Filtered pulse-like signal")
    axes[0].set_xlabel("Time (seconds)")
    axes[0].set_ylabel("Relative signal")
    axes[0].legend()

    skin_band = (skin_frequencies >= LOW_HZ) & (skin_frequencies <= HIGH_HZ)
    axes[1].plot(
        skin_frequencies[skin_band] * 60.0,
        skin_power[skin_band],
        color="purple",
        label="Skin POS spectrum",
    )
    axes[1].axvline(
        x=pulse_bpm,
        color="red",
        linestyle="--",
        label=f"Selected peak: {pulse_bpm:.1f} BPM",
    )
    axes[1].set_title("In-band power spectrum")
    axes[1].set_xlabel("Cycles per minute (BPM scale)")
    axes[1].set_ylabel("Power spectral density")
    axes[1].legend()

    figure.tight_layout()
    figure.savefig(output_path, dpi=150)
    plt.close(figure)


def analyze_video(video_path, output_dir, inspect_only=False):
    output_dir.mkdir(parents=True, exist_ok=True)
    data = extract_video(video_path, output_dir)
    save_raw_rgb_plot(data["times"], data["rgb"], output_dir / "raw_rgb.png")

    if inspect_only:
        print(f"Saved {output_dir / 'roi_preview.jpg'}")
        print(f"Saved {output_dir / 'raw_rgb.png'}")
        return data

    pulse = pos_signal(data["rgb"], data["fps"])
    filtered = bandpass(pulse, data["fps"])
    skin_frequency, skin_share, skin_frequencies, skin_power = dominant_frequency(
        filtered, data["fps"]
    )
    pulse_bpm = skin_frequency * 60.0

    save_analysis_plot(
        data["times"],
        filtered,
        skin_frequencies,
        skin_power,
        pulse_bpm,
        output_dir / "pulse_analysis.png",
    )

    data.update(
        {
            "filtered": filtered,
            "pulse_bpm": pulse_bpm,
            "skin_share": skin_share,
        }
    )

    print(f"Experimental video BPM: {pulse_bpm:.1f}")
    print(f"Saved {output_dir / 'pulse_analysis.png'}")
    print("Educational output only. This is not a medical device.")
    return data


def main():
    args = build_parser().parse_args()
    analyze_video(
        args.video,
        Path("outputs"),
        inspect_only=args.inspect,
    )


if __name__ == "__main__":
    main()
Judge the signal evidence

A BPM value can look precise even when the underlying signal is weak. The waveform and spectrum show whether the number came from a visible repeating pattern or an uncertain collection of peaks.

  • Return to the outputs folder from the inspection step.
  • Open pulse_analysis.png in your computer's image viewer.
  • Check the upper panel for an oscillating filtered trace instead of continuous drift.
  • Check the lower panel for a marked peak between 42 and 180 BPM.

You should see the filtered waveform above an in-band spectrum with one selected peak. That marked peak corresponds to the experimental BPM printed in the terminal.

When should you distrust the estimate?

A flat waveform gives the spectrum little meaningful variation to analyze. Several peaks with nearly equal power also make the selected maximum unstable.

Treat either pattern as a reason to improve the recording conditions and try again. Forcing a cleaner number would hide uncertainty instead of fixing the signal.

Does the plot look uncertain?

  • Re-record under steady diffuse lighting if the filtered trace remains dominated by broad drift.
  • Keep your face still if the waveform contains large abrupt changes.
  • Use a longer steady section if several spectral peaks have similar heights.

Want help interpreting the evidence? Help me assess whether my filtered waveform and spectrum support a stable experimental BPM estimate.

Your video now produces a filtered pulse-like trace and an experimental BPM candidate. Next, you'll compare that candidate with a manual count and test it for compression artifacts before deciding how much trust it deserves.

Challenge the Result

Your filtered signal now has a plausible peak in its power spectrum. Background flicker or video compression can still create a similar peak.

You will compare the estimate with a rough wrist count. You will also use Claude Code to make the program search for shared background or keyframe patterns before reporting its result.

In this step, get ready to:
  • Take a 30-second wrist count for a rough personal comparison.
  • Add background-spectrum checks plus keyframe-cadence checks to the program.
  • Generate a report that labels suspicious evidence as PASS or WARNING.
Take the manual comparison

A manual wrist count gives you a second rough estimate from the same period of rest. It is a personal cross-check with limited precision.

  • Sit quietly after recording your video.
  • Place two fingers over the pulse point on your wrist.
  • Keep your thumb away from the pulse point.
  • Count the beats for 30 seconds.
  • Record the integer here: your 30-second wrist count.

How is the count used?

The program multiplies your 30-second count by 2 to estimate manual wrist BPM. It then reports the absolute difference from the experimental video BPM.

A small difference is encouraging evidence from this one experiment. It does not validate the program as a medical measurement.

Add the artifact challenge

The face and background can share a periodic signal when lighting changes across the whole frame. Video keyframes can also create repeated discontinuities that resemble a physiological rhythm.

The final program keeps suspicious frequencies visible. It reports the evidence instead of deleting a peak and treating the remaining signal as true.

  • Switch back to the Claude Code session from the previous step.
  • Finish the artifact report by pasting this prompt:
Finish pulse_reader.py with a --wrist-count integer option and an artifact report.

The wrist count represents beats counted for 30 seconds, so report wrist BPM as count * 2 and the absolute difference from the experimental video BPM.

During video extraction, after each successful frame read, inspect cv.CAP_PROP_FRAME_TYPE. Record the timestamp when its ASCII value is 73, meaning an I-frame, and estimate a keyframe frequency from the median interval when at least two intervals exist. This property is FFmpeg-backend-only, so report unavailable instead of failing when it is not exposed.

Also retain the background patch's mean green trace, run it through the same 0.7 to 3.0 Hz filter, and compute its periodogram. Create a transparent heuristic: flag a shared-background artifact only when the background's dominant in-band frequency is within one spectral bin of the skin peak and its peak share is at least half the skin peak share. Flag a keyframe match only when the estimated keyframe frequency lies inside the pulse band and is within one spectral bin of the skin peak. Do not delete or notch any frequency automatically.

Write outputs/report.txt with the video BPM, wrist BPM if supplied, absolute difference, background peak, keyframe rate or unavailable, artifact reasons, and PASS or WARNING. State clearly that PASS does not make the tool medical-grade. Update pulse_analysis.png to include the background spectrum for comparison. Review all imports and return the final run commands.

What does this change add?

  • The --wrist-count option gives the program your 30-second count for the manual comparison.
  • The background check compares the dominant background frequency with the selected skin frequency. Its peak-share threshold prevents every weak background peak from triggering a warning.
  • The OpenCV property cv.CAP_PROP_FRAME_TYPE can identify an I-frame through the ASCII value 73 when the video backend exposes that information.
  • The final report preserves suspicious evidence. It never applies automatic notch filtering.
  • Review the proposed changes to pulse_reader.py.
  • Confirm that the program flags suspicious peaks without deleting them.
  • Approve the file write after the requested checks are present.
  • Allow the test command if Claude Code asks for execution permission.

Claude Code should finish with updated run commands plus a summary of the artifact checks. The completed file should now create outputs/report.txt during a full run.

Missing part of the artifact report?

  • Check that build_parser includes the --wrist-count argument.
  • Check that extract_video returns both background_green and keyframe_times.
  • Check that analyze_video calls write_report after the two artifact checks.

Still missing a requirement? Help me compare my pulse_reader.py with the requested artifact-report behavior.

✔️ Awesome, I've got everything!

Great. Make sure Claude Code saved the final pulse_reader.py before you run the completed analysis.

ⓧ I'd like to double check the full code

Compare your pulse_reader.py with this final reference:

import argparse
from pathlib import Path

import cv2 as cv
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import butter, periodogram, sosfiltfilt

LOW_HZ = 0.7
HIGH_HZ = 3.0
CASCADE_NAME = "haarcascade_frontalface_default.xml"


def build_parser():
    parser = argparse.ArgumentParser(
        description="Educational phone-video pulse experiment. Not a medical device."
    )
    parser.add_argument("video", type=Path, help="Path to a face video")
    parser.add_argument(
        "--inspect",
        action="store_true",
        help="Only create the ROI preview and raw RGB plot",
    )
    parser.add_argument(
        "--wrist-count",
        type=int,
        default=None,
        help="Beats counted manually for 30 seconds",
    )
    return parser


def scaled_rect(face, x_start, y_start, x_end, y_end, frame_width, frame_height):
    x, y, width, height = [int(value) for value in face]
    x1 = max(0, x + int(width * x_start))
    y1 = max(0, y + int(height * y_start))
    x2 = min(frame_width, x + int(width * x_end))
    y2 = min(frame_height, y + int(height * y_end))
    if x2 <= x1 or y2 <= y1:
        raise ValueError("A calculated face patch is empty.")
    return x1, y1, x2, y2


def choose_background(face, frame_width, frame_height):
    patch_width = max(20, int(frame_width * 0.18))
    patch_height = max(20, int(frame_height * 0.18))
    candidates = [
        (0, 0, patch_width, patch_height),
        (frame_width - patch_width, 0, frame_width, patch_height),
        (0, frame_height - patch_height, patch_width, frame_height),
        (
            frame_width - patch_width,
            frame_height - patch_height,
            frame_width,
            frame_height,
        ),
    ]
    x, y, width, height = [int(value) for value in face]
    face_center = (x + width / 2.0, y + height / 2.0)

    def distance_squared(rect):
        x1, y1, x2, y2 = rect
        center = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
        return (center[0] - face_center[0]) ** 2 + (center[1] - face_center[1]) ** 2

    return max(candidates, key=distance_squared)


def detect_regions(first_frame):
    frame_height, frame_width = first_frame.shape[:2]
    cascade_path = cv.data.haarcascades + CASCADE_NAME
    cascade = cv.CascadeClassifier(cascade_path)
    if cascade.empty():
        raise RuntimeError(f"Could not load face cascade: {cascade_path}")

    gray = cv.cvtColor(first_frame, cv.COLOR_BGR2GRAY)
    gray = cv.equalizeHist(gray)
    minimum = max(60, min(frame_width, frame_height) // 10)
    faces = cascade.detectMultiScale(
        gray,
        scaleFactor=1.1,
        minNeighbors=5,
        minSize=(minimum, minimum),
    )
    if len(faces) == 0:
        raise RuntimeError("No face was found in the first frame.")

    face = max(faces, key=lambda rect: int(rect[2]) * int(rect[3]))
    skin_regions = [
        scaled_rect(face, 0.30, 0.12, 0.70, 0.30, frame_width, frame_height),
        scaled_rect(face, 0.15, 0.52, 0.38, 0.74, frame_width, frame_height),
        scaled_rect(face, 0.62, 0.52, 0.85, 0.74, frame_width, frame_height),
    ]
    background_region = choose_background(face, frame_width, frame_height)
    return tuple(int(value) for value in face), skin_regions, background_region


def mean_bgr(frame, regions):
    pixel_groups = []
    for x1, y1, x2, y2 in regions:
        pixel_groups.append(frame[y1:y2, x1:x2].reshape(-1, 3))
    pixels = np.concatenate(pixel_groups, axis=0)
    return np.mean(pixels, axis=0)


def save_preview(frame, face, skin_regions, background_region, output_path):
    preview = frame.copy()
    x, y, width, height = face
    cv.rectangle(preview, (x, y), (x + width, y + height), (0, 255, 255), 3)
    for x1, y1, x2, y2 in skin_regions:
        cv.rectangle(preview, (x1, y1), (x2, y2), (0, 255, 0), 3)
    x1, y1, x2, y2 = background_region
    cv.rectangle(preview, (x1, y1), (x2, y2), (255, 0, 0), 3)
    if not cv.imwrite(str(output_path), preview):
        raise RuntimeError(f"Could not write {output_path}")


def extract_video(video_path, output_dir):
    if not video_path.is_file():
        raise FileNotFoundError(f"Video not found: {video_path}")

    capture = cv.VideoCapture(str(video_path))
    if not capture.isOpened():
        raise RuntimeError(f"Could not open video: {video_path}")
    capture.set(cv.CAP_PROP_ORIENTATION_AUTO, 1)

    fps = float(capture.get(cv.CAP_PROP_FPS))
    if fps <= 0:
        capture.release()
        raise RuntimeError("The video backend did not report a usable FPS.")

    ok, frame = capture.read()
    if not ok:
        capture.release()
        raise RuntimeError("The video has no readable frames.")

    frame_height, frame_width = frame.shape[:2]
    face, skin_regions, background_region = detect_regions(frame)
    save_preview(
        frame,
        face,
        skin_regions,
        background_region,
        output_dir / "roi_preview.jpg",
    )

    times = []
    skin_rgb = []
    background_green = []
    keyframe_times = []
    frame_index = 0

    while ok:
        timestamp = float(capture.get(cv.CAP_PROP_POS_MSEC)) / 1000.0
        if times and timestamp <= times[-1]:
            timestamp = times[-1] + 1.0 / fps
        elif not times and timestamp < 0:
            timestamp = 0.0

        skin_mean = mean_bgr(frame, skin_regions)
        background_mean = mean_bgr(frame, [background_region])
        skin_rgb.append(skin_mean[::-1])
        background_green.append(float(background_mean[1]))
        times.append(timestamp)

        frame_type = int(capture.get(cv.CAP_PROP_FRAME_TYPE))
        if frame_type == 73:
            keyframe_times.append(timestamp)

        frame_index += 1
        ok, frame = capture.read()

    capture.release()

    if frame_index < max(64, int(10 * fps)):
        raise RuntimeError("Record at least 10 seconds of usable video.")

    source_times = np.asarray(times, dtype=float)
    source_times = source_times - source_times[0]
    if source_times[-1] <= 0:
        source_times = np.arange(frame_index, dtype=float) / fps

    uniform_times = np.arange(
        0.0,
        source_times[-1] + 0.5 / fps,
        1.0 / fps,
        dtype=float,
    )
    skin_rgb_array = np.asarray(skin_rgb, dtype=float)
    uniform_rgb = np.column_stack(
        [
            np.interp(uniform_times, source_times, skin_rgb_array[:, channel])
            for channel in range(3)
        ]
    )
    uniform_background = np.interp(
        uniform_times,
        source_times,
        np.asarray(background_green, dtype=float),
    )

    return {
        "times": uniform_times,
        "rgb": uniform_rgb,
        "background_green": uniform_background,
        "keyframe_times": np.asarray(keyframe_times, dtype=float),
        "fps": fps,
        "face": face,
        "skin_regions": skin_regions,
        "background_region": background_region,
        "width": frame_width,
        "height": frame_height,
    }


def save_raw_rgb_plot(times, rgb, output_path):
    channel_mean = np.mean(rgb, axis=0)
    relative = 100.0 * (rgb / channel_mean - 1.0)
    figure, axis = plt.subplots(figsize=(10, 4))
    axis.plot(times, relative[:, 0], color="red", label="Red")
    axis.plot(times, relative[:, 1], color="green", label="Green")
    axis.plot(times, relative[:, 2], color="blue", label="Blue")
    axis.set_title("Raw skin-patch RGB change")
    axis.set_xlabel("Time (seconds)")
    axis.set_ylabel("Change from channel mean (%)")
    axis.legend()
    figure.tight_layout()
    figure.savefig(output_path, dpi=150)
    plt.close(figure)


def pos_signal(rgb, fps):
    sample_count = len(rgb)
    pulse = np.zeros(sample_count, dtype=float)
    window_length = max(3, int(round(1.6 * fps)))
    if sample_count < window_length:
        raise ValueError("The recording is too short for the POS window.")

    for end in range(window_length - 1, sample_count):
        start = end - window_length + 1
        window = rgb[start : end + 1].T
        temporal_mean = np.mean(window, axis=1, keepdims=True)
        normalized = window / temporal_mean
        s1 = normalized[1] - normalized[2]
        s2 = normalized[1] + normalized[2] - 2.0 * normalized[0]
        denominator = float(np.std(s2))
        if denominator <= 1e-12:
            denominator = 1e-12
        alpha = float(np.std(s1)) / denominator
        segment = s1 + alpha * s2
        pulse[start : end + 1] += segment - np.mean(segment)

    return pulse


def bandpass(signal, fps):
    sos = butter(
        3,
        [LOW_HZ, HIGH_HZ],
        btype="bandpass",
        fs=fps,
        output="sos",
    )
    return sosfiltfilt(sos, signal)


def dominant_frequency(signal, fps):
    frequencies, power = periodogram(
        signal,
        fs=fps,
        window="hann",
        scaling="density",
    )
    band = (frequencies >= LOW_HZ) & (frequencies <= HIGH_HZ)
    band_frequencies = frequencies[band]
    band_power = power[band]
    if len(band_frequencies) == 0:
        raise RuntimeError("No spectrum bins landed inside the pulse band.")
    peak_index = int(np.argmax(band_power))
    total_power = float(sum(band_power))
    peak_share = 0.0 if total_power <= 0 else float(band_power[peak_index]) / total_power
    return (
        float(band_frequencies[peak_index]),
        peak_share,
        frequencies,
        power,
    )


def estimate_keyframe_frequency(keyframe_times):
    if len(keyframe_times) < 3:
        return None
    intervals = np.diff(keyframe_times)
    positive_intervals = intervals[intervals > 0]
    if len(positive_intervals) < 2:
        return None
    median_interval = float(np.median(positive_intervals))
    if median_interval <= 0:
        return None
    return 1.0 / median_interval


def save_analysis_plot(
    times,
    filtered,
    skin_frequencies,
    skin_power,
    background_frequencies,
    background_power,
    pulse_bpm,
    output_path,
):
    figure, axes = plt.subplots(2, 1, figsize=(10, 7))
    axes[0].plot(times, filtered, color="purple", label="Filtered POS")
    axes[0].set_title("Filtered pulse-like signal")
    axes[0].set_xlabel("Time (seconds)")
    axes[0].set_ylabel("Relative signal")
    axes[0].legend()

    skin_band = (skin_frequencies >= LOW_HZ) & (skin_frequencies <= HIGH_HZ)
    background_band = (background_frequencies >= LOW_HZ) & (
        background_frequencies <= HIGH_HZ
    )
    axes[1].plot(
        skin_frequencies[skin_band] * 60.0,
        skin_power[skin_band],
        color="purple",
        label="Skin POS spectrum",
    )
    axes[1].plot(
        background_frequencies[background_band] * 60.0,
        background_power[background_band],
        color="gray",
        label="Background green spectrum",
    )
    axes[1].axvline(
        x=pulse_bpm,
        color="red",
        linestyle="--",
        label=f"Selected peak: {pulse_bpm:.1f} BPM",
    )
    axes[1].set_title("In-band power spectrum")
    axes[1].set_xlabel("Cycles per minute (BPM scale)")
    axes[1].set_ylabel("Power spectral density")
    axes[1].legend()

    figure.tight_layout()
    figure.savefig(output_path, dpi=150)
    plt.close(figure)


def write_report(
    output_path,
    pulse_bpm,
    wrist_count,
    background_bpm,
    keyframe_frequency,
    artifact_reasons,
):
    lines = [
        "Invisible Pulse Reader report",
        "",
        f"Experimental video BPM: {pulse_bpm:.1f}",
    ]
    if wrist_count is None:
        lines.append("Manual wrist BPM: not supplied")
    else:
        wrist_bpm = wrist_count * 2
        lines.append(f"Manual wrist BPM: {wrist_bpm}")
        lines.append(f"Absolute difference: {abs(pulse_bpm - wrist_bpm):.1f} BPM")

    lines.append(f"Background dominant peak: {background_bpm:.1f} BPM")
    if keyframe_frequency is None:
        lines.append("Estimated keyframe rate: unavailable")
    else:
        lines.append(
            f"Estimated keyframe rate: {keyframe_frequency:.3f} Hz "
            f"({keyframe_frequency * 60.0:.1f} cycles/min)"
        )

    lines.append("")
    if artifact_reasons:
        lines.append("Artifact status: WARNING")
        for reason in artifact_reasons:
            lines.append(f"- {reason}")
    else:
        lines.append("Artifact status: PASS")
        lines.append("- No tested background or keyframe match crossed the heuristic.")

    lines.extend(
        [
            "",
            "PASS does not make this tool medical-grade.",
            "Do not use this result for diagnosis, emergencies, or determining whether someone is alive.",
        ]
    )
    output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def analyze_video(video_path, output_dir, wrist_count=None, inspect_only=False):
    output_dir.mkdir(parents=True, exist_ok=True)
    data = extract_video(video_path, output_dir)
    save_raw_rgb_plot(data["times"], data["rgb"], output_dir / "raw_rgb.png")

    if inspect_only:
        print(f"Saved {output_dir / 'roi_preview.jpg'}")
        print(f"Saved {output_dir / 'raw_rgb.png'}")
        return data

    pulse = pos_signal(data["rgb"], data["fps"])
    filtered = bandpass(pulse, data["fps"])
    background_filtered = bandpass(
        data["background_green"] - np.mean(data["background_green"]),
        data["fps"],
    )

    skin_frequency, skin_share, skin_frequencies, skin_power = dominant_frequency(
        filtered, data["fps"]
    )
    (
        background_frequency,
        background_share,
        background_frequencies,
        background_power,
    ) = dominant_frequency(background_filtered, data["fps"])

    pulse_bpm = skin_frequency * 60.0
    background_bpm = background_frequency * 60.0
    frequency_resolution = (
        float(skin_frequencies[1] - skin_frequencies[0])
        if len(skin_frequencies) > 1
        else data["fps"] / len(filtered)
    )

    artifact_reasons = []
    background_matches = (
        abs(background_frequency - skin_frequency) <= frequency_resolution
        and background_share >= 0.5 * skin_share
    )
    if background_matches:
        artifact_reasons.append(
            "The dominant background peak matches the skin peak within one spectral bin."
        )

    keyframe_frequency = estimate_keyframe_frequency(data["keyframe_times"])
    keyframe_matches = (
        keyframe_frequency is not None
        and LOW_HZ <= keyframe_frequency <= HIGH_HZ
        and abs(keyframe_frequency - skin_frequency) <= frequency_resolution
    )
    if keyframe_matches:
        artifact_reasons.append(
            "The skin peak matches the estimated I-frame cadence within one spectral bin."
        )

    save_analysis_plot(
        data["times"],
        filtered,
        skin_frequencies,
        skin_power,
        background_frequencies,
        background_power,
        pulse_bpm,
        output_dir / "pulse_analysis.png",
    )
    write_report(
        output_dir / "report.txt",
        pulse_bpm,
        wrist_count,
        background_bpm,
        keyframe_frequency,
        artifact_reasons,
    )

    data.update(
        {
            "filtered": filtered,
            "pulse_bpm": pulse_bpm,
            "background_bpm": background_bpm,
            "keyframe_frequency": keyframe_frequency,
            "artifact_reasons": artifact_reasons,
        }
    )

    print(f"Experimental video BPM: {pulse_bpm:.1f}")
    print(f"Artifact status: {'WARNING' if artifact_reasons else 'PASS'}")
    print(f"Saved {output_dir / 'pulse_analysis.png'}")
    print(f"Saved {output_dir / 'report.txt'}")
    print("Educational output only. This is not a medical device.")
    return data


def main():
    args = build_parser().parse_args()
    if args.wrist_count is not None and args.wrist_count < 0:
        raise ValueError("--wrist-count must be zero or greater.")
    analyze_video(
        args.video,
        Path("outputs"),
        wrist_count=args.wrist_count,
        inspect_only=args.inspect,
    )


if __name__ == "__main__":
    main()

This reference preserves the inspection workflow. It adds the wrist comparison plus the background and keyframe artifact checks used by the final report.

Run the finished reader

The full run updates the analysis plot with the background spectrum. It also writes the evidence summary to outputs/report.txt.

Before you run it, do you expect your recording to receive PASS or WARNING?

  • Replace 36 in your platform's example with your 30-second wrist count.
  • Run the finished analysis with the command for your platform:

macOS

.venv/bin/python pulse_reader.py face.mp4 --wrist-count 36

This runs the full analysis with an example 30-second count of 36. The virtual environment supplies the pinned scientific packages.

Windows

.\.venv\Scripts\python.exe pulse_reader.py face.mp4 --wrist-count 36

This runs the full analysis with an example 30-second count of 36. The virtual environment supplies the pinned scientific packages.

You should see Experimental video BPM plus an Artifact status of PASS or WARNING. You should also see confirmation that the updated plot and report were saved.

  • Return to the invisible-pulse folder in your computer's file browser.
  • Open the outputs folder.
  • Open report.txt to inspect the recorded evidence.
  • Open pulse_analysis.png to compare the skin POS spectrum with the background green spectrum.

The report should list your experimental video BPM plus doubled wrist BPM. It should also show their absolute difference.

You should see a background peak plus an estimated keyframe rate or unavailable when the backend cannot provide enough timing information. The final status should be PASS or WARNING.

How should I read the status?

A WARNING means the selected skin peak overlaps suspicious background or keyframe evidence under the program's heuristic. Keep the peak visible so you can inspect why it was challenged.

A PASS means neither tested heuristic crossed its threshold. The result remains an educational signal estimate with no medical use.

Report or background spectrum missing?

  • Confirm that your command omitted --inspect because inspection mode stops before the final analysis.
  • Confirm that Claude Code saved the final pulse_reader.py before you ran it.
  • Check the terminal for the first traceback line that points into pulse_reader.py.

Need help with the failed run? Help me debug why my completed pulse reader did not create report.txt or the updated background spectrum.

You have now built the responsible part of the experiment. Your program compares another measurement and exposes suspicious evidence before presenting its conclusion.

Secret mission

Make the Invisible Pulse Visible

Turn the filtered pulse signal into a local video where your forehead and cheek patches visibly redden and fade. You will reuse the trusted analysis in pulse_reader.py while leaving the rest of each frame unchanged.

Clean Up Your Resources

Clean Up Your Resources

Your pulse reader runs locally, so its files create no ongoing cloud cost. Decide whether to keep the local project, pause by cancelling Claude Pro before renewal, or delete the private recording and project folder.

Cost warning

Claude Pro renews monthly at the documented US price of $20 per month. Local currency plus tax can vary.

Optional usage credits are separate. They can create additional charges if enabled.

Resources you used:

  • Claude Pro subscription with monthly renewal until cancellation.
  • Private face recording face.mp4.
  • Local project folder invisible-pulse. It contains the Python virtual environment .venv plus your source files.
  • Generated outputs folder containing the annotated preview, signal plots, report, and magnified AVI.

Keep everything running

No action is needed. Choose this option if you plan to keep experimenting with the pulse reader or colour magnifier.

  • Claude Pro continues to renew monthly until you cancel the subscription.
  • Your invisible-pulse folder remains ready for future analysis.
  • Keep face.mp4 private if you retain the recording.

Pause - I'll come back to this later

This option stops the recurring subscription while keeping your local experiment ready for another session.

  • Cancel Claude Pro before renewal through the subscription controls on the Claude account used for this project.
  • Keep the invisible-pulse folder on your computer.
  • Keep face.mp4 private while the project is paused.

Your existing Python program remains usable after the subscription ends. Its code and installed packages are stored locally.

Delete - I don't want to use this again

Deleting the folder is permanent. The steps below remove the private recording first so you stay in control of that file.

  • Cancel Claude Pro before renewal through the subscription controls on the Claude account used for this project.
  • In Finder on macOS or File Explorer on Windows, delete face.mp4 from invisible-pulse.
  • Empty Trash on macOS or Recycle Bin on Windows to remove the private recording from local storage.
  • In Finder on macOS or File Explorer on Windows, delete the remaining invisible-pulse folder from its parent folder.
  • Empty Trash on macOS or Recycle Bin on Windows again to remove the project files.
  • Confirm the parent folder no longer contains invisible-pulse.

Nice Work!

Nice Work!

You did it! Your local remote photoplethysmography experiment now turns tiny facial colour changes into an experimental BPM estimate.

You've learned how to:

  • Directed Claude Code to build a Python workflow. Reviewed every file change before acceptance. Checked algorithm details before running the program.
  • Used OpenCV to detect the largest face in your video. Sampled a fixed forehead region. Sampled two fixed cheek regions. Sampled a background patch for comparison. Generated an annotated ROI preview. Plotted raw RGB traces from the selected skin pixels.
  • Applied the POS projection to suppress shared colour changes. Used Butterworth band-pass filtering to isolate the pulse band. Estimated experimental BPM from the power spectrum. Compared the estimate with your doubled 30-second wrist count. Tested the background spectrum. Tested available keyframe timing. Reported PASS or WARNING without treating the result as medical evidence.
  • Completed the optional Secret Mission. Reused analyze_video from pulse_reader.py inside magnify.py. Produced outputs/magnified_pulse.avi with pulse-locked red changes confined to the three skin patches.

Ready to quiz yourself?