What is the Generator Pattern?

A generator is a Python function that pauses execution and yields values incrementally using the yield keyword. It maintains its state between calls, making it ideal for:


Key Components in Your Video Analyzer

Component Role
yield statement Pauses execution and returns a frame's results
run_analysis() method Becomes a generator that processes frames on demand
for loop Iterates through the generator, receiving results as they're produced
finally block Ensures cleanup happens even if processing is interrupted

How It Works in Your Code

def run_analysis(self):
    """Generator that processes frames on demand"""
    try:
        while self.cap.isOpened():
            # 1. Get frame from video
            ret, frame = self.cap.read()
            if not ret: break

            # 2. Process frame
            processed_frame = self._process_frame(frame)

            # 3. Yield results IMMEDIATELY
            yield {
                'frame': processed_frame,
                'warnings_posture': current_warnings,
                'metrics': current_metrics
            }

    finally:
        # 4. Final cleanup when done
        self._release_resources()
        self._generate_final_plot()

Execution Flow

sequenceDiagram
    participant Caller
    participant Generator
    participant VideoFile

    Caller->>Generator: Start processing
    loop Frame-by-Frame
        Generator->>VideoFile: Get next frame
        VideoFile->>Generator: Return frame
        Generator->>Generator: Process frame
        Generator->>Caller: Yield frame results
        Caller->>Caller: Handle results immediately
    end
    Generator->>Generator: Cleanup resources
    Generator->>Caller: Return final outputs


Example Usage

# Initialize analyzer
analyzer = CPRAnalyzer("cpr_video.mp4")

# Process in real-time
for frame_data in analyzer.run_analysis():
    # Immediate access to frame results
    print(f"Frame {frame_data['frame_number']}")
    print(f"Posture warnings: {frame_data['warnings_posture']}")

    # Optional: Preview processed frame
    cv2.imshow('CPR Analysis', frame_data['frame'])
    cv2.waitKey(1)

# After full processing
print(f"Saved video: {analyzer.output_video_path}")
print(f"Analysis plot: {analyzer.plot_path}")

Key Advantages Over Batch Processing

Generator Pattern Traditional Batch Processing
Memory Usage Constant (per-frame) Scales with video length
Latency Immediate feedback Wait until entire video completes
User Interaction Can pause/stop mid-process All-or-nothing execution
Failure Recovery Resume from last frame Restart entire process