### Basic Screencapture with PIL Source: https://github.com/zaatra/rapidshot/blob/main/README.md Demonstrates how to create a ScreenCapture instance, grab a frame from the primary monitor, and display it using Pillow (PIL). Requires the Pillow library to be installed. ```python import rapidshot # Create a ScreenCapture instance on the primary monitor screencapture = rapidshot.create() # Take a screencapture frame = screencapture.grab() # Display the screencapture from PIL import Image Image.fromarray(frame).show() ``` -------------------------------- ### Install RapidShot Package Source: https://github.com/zaatra/rapidshot/blob/main/README.md Installs the RapidShot library using pip. Different variants are available for OpenCV support, NVIDIA GPU acceleration, or all dependencies. ```bash pip install rapidshot ``` ```bash pip install rapidshot[cv2] ``` ```bash pip install rapidshot[gpu] ``` ```bash pip install rapidshot[all] ``` -------------------------------- ### Query Graphics Device and Output Information Source: https://context7.com/zaatra/rapidshot/llms.txt Provides methods to list available graphics adapters (GPUs) and monitor outputs for multi-GPU and multi-monitor setups. It demonstrates how to retrieve device information using `rapidshot.device_info()` and output information using `rapidshot.output_info()`, and how to create capture instances for specific configurations. Includes cleanup functions. ```python import rapidshot # List all available devices (GPUs) print("Available Graphics Devices:") print(rapidshot.device_info()) # Output example: # Device[0]: NVIDIA GeForce RTX 3080 # Device[1]: Intel UHD Graphics 630 # List all available outputs (monitors) per device print("\nAvailable Outputs:") print(rapidshot.output_info()) # Output example: # Device[0] Output[0]: Resolution:(1920, 1080) Rotation:0 Primary:True # Device[0] Output[1]: Resolution:(2560, 1440) Rotation:0 Primary:False # Device[1] Output[0]: Resolution:(1920, 1080) Rotation:0 Primary:False # Create captures for specific configurations primary = rapidshot.create(device_idx=0, output_idx=0) secondary = rapidshot.create(device_idx=0, output_idx=1) # Cleanup rapidshot.clean_up() # Release all capture instances rapidshot.reset() # Complete library reset ``` -------------------------------- ### Continuous Capture and Processing Source: https://github.com/zaatra/rapidshot/blob/main/README.md Illustrates how to start continuous screen capture at a specified frame rate, retrieve frames in a loop, and then stop the capture. This is useful for real-time applications. ```python # Start capturing at 60 FPS screencapture.start(target_fps=60) # Get the latest frame for i in range(1000): image = screencapture.get_latest_frame() # Blocks until new frame is available # Process the frame... # Stop capturing screencapture.stop() ``` -------------------------------- ### Video Recording with OpenCV Source: https://github.com/zaatra/rapidshot/blob/main/README.md Demonstrates recording the screen to a video file using OpenCV. It requires RapidShot to be installed with OpenCV support (`rapidshot[cv2]`) and the OpenCV library itself. ```python import rapidshot import cv2 # Create a ScreenCapture instance with BGR color format for OpenCV screencapture = rapidshot.create(output_color="BGR") # Start capturing at 30 FPS in video mode screencapture.start(target_fps=30, video_mode=True) # Create a video writer writer = cv2.VideoWriter( "video.mp4", cv2.VideoWriter_fourcc(*"mp4v"), 30, (1920, 1080) ) # Record for 10 seconds (300 frames at 30 FPS) for i in range(300): writer.write(screencapture.get_latest_frame()) # Clean up screencapture.stop() writer.release() ``` -------------------------------- ### NVIDIA GPU Accelerated Capture Source: https://github.com/zaatra/rapidshot/blob/main/README.md Shows how to initialize RapidShot for NVIDIA GPU acceleration, which can significantly improve performance for capture and processing tasks. Requires `rapidshot[gpu]` installation. ```python # Create a ScreenCapture instance with NVIDIA GPU acceleration screencapture = rapidshot.create(nvidia_gpu=True) # Screenshots will be processed on the GPU for improved performance frame = screencapture.grab() ``` -------------------------------- ### GPU-Accelerated Capture with CuPy Source: https://context7.com/zaatra/rapidshot/llms.txt Demonstrates how to enable NVIDIA GPU acceleration using CuPy for high-performance screen capture and processing. It shows how to create a capture instance with GPU support, capture frames as CuPy arrays, perform GPU operations, and convert back to NumPy when necessary. Requires CuPy to be installed. ```python import rapidshot import numpy as np try: import cupy as cp # Create GPU-accelerated capture instance screencapture = rapidshot.create( output_color="RGB", nvidia_gpu=True, max_buffer_len=256 ) screencapture.start(target_fps=120) for i in range(1000): # Returns CuPy array when as_numpy=False frame_gpu = screencapture.get_latest_frame(as_numpy=False) if frame_gpu is not None: # Perform GPU operations directly on CuPy array mean_gpu = cp.mean(frame_gpu) # Convert to NumPy only when needed if i % 100 == 0: frame_cpu = cp.asnumpy(frame_gpu) print(f"Frame {i}: GPU mean={float(mean_gpu):.2f}") screencapture.stop() screencapture.release() except ImportError: print("CuPy not available. Install with: pip install rapidshot[gpu]") ``` -------------------------------- ### Continuous Capture Mode Source: https://context7.com/zaatra/rapidshot/llms.txt Start a background capture thread that continuously grabs frames at a target frame rate. This is useful for real-time applications. Remember to stop and release resources. ```APIDOC ## Continuous Capture Mode ### Description Start a background capture thread that continuously grabs frames at a target frame rate for real-time applications. ### Method `screencapture.start(target_fps=30, video_mode=False)` ### Parameters #### Required Parameters - **target_fps** (int) - The desired frames per second for continuous capture. #### Optional Parameters - **video_mode** (bool) - If True, duplicates the last frame if no new frame is available. Defaults to False. ### Request Example ```python import rapidshot import time screencapture = rapidshot.create(output_color="RGB") # Start capturing at 60 FPS screencapture.start(target_fps=60, video_mode=False) try: for i in range(300): # Capture 300 frames frame = screencapture.get_latest_frame() if frame is not None: # Process frame (e.g., object detection, analysis) print(f"Frame {i}: {frame.shape}") time.sleep(0.001) # Minimal delay for processing except KeyboardInterrupt: print("Capture interrupted") finally: screencapture.stop() screencapture.release() ``` ### Response No direct response for start; operates in the background. ### Get Latest Frame #### Method `screencapture.get_latest_frame()` ### Description Retrieve the most recently captured frame from the continuous capture thread. ### Response #### Success Response - **frame** (numpy.ndarray) - The latest captured frame. Returns None if no frame is available yet or capture has stopped. ### Stop Continuous Capture #### Method `screencapture.stop()` ### Description Stop the background capture thread. ### Cleanup #### Method `screencapture.release()` ### Description Release resources associated with the screen capture instance. ``` -------------------------------- ### Implement Instant Replay System with RapidShot and OpenCV Source: https://context7.com/zaatra/rapidshot/llms.txt This Python code demonstrates how to create an instant replay system using a circular buffer (deque) to store the last N seconds of screen activity captured by RapidShot. It utilizes OpenCV for writing the buffered frames into a video file. Ensure OpenCV and RapidShot are installed. ```python import rapidshot import cv2 from collections import deque import time class InstantReplay: def __init__(self, fps=60, duration_sec=10): self.fps = fps self.buffer = deque(maxlen=fps * duration_sec) self.capture = rapidshot.create(output_color="BGR") self.capture.start(target_fps=fps, video_mode=True) self.is_recording = True def record_loop(self): """Continuously record frames to circular buffer""" while self.is_recording: frame = self.capture.get_latest_frame() if frame is not None: self.buffer.append(frame.copy()) def save_replay(self, filename="replay.mp4"): """Save buffered frames to video file""" if len(self.buffer) == 0: print("No frames to save") return height, width = self.buffer[0].shape[:2] fourcc = cv2.VideoWriter_fourcc(*"mp4v") writer = cv2.VideoWriter(filename, fourcc, self.fps, (width, height)) for frame in self.buffer: writer.write(frame) writer.release() print(f"Saved {len(self.buffer)} frames to {filename}") def stop(self): """Stop recording and cleanup""" self.is_recording = False self.capture.stop() self.capture.release() # Usage replay = InstantReplay(fps=60, duration_sec=10) # Run replay recording in background import threading record_thread = threading.Thread(target=replay.record_loop) record_thread.start() # Simulate some activity, then save replay time.sleep(15) # Record for 15 seconds replay.save_replay("last_10_seconds.mp4") replay.stop() record_thread.join() ``` -------------------------------- ### Efficient Memory Pool Management with RapidShot Source: https://context7.com/zaatra/rapidshot/llms.txt This Python example showcases how to leverage RapidShot's memory pool system for high-frequency capture scenarios. By setting `max_buffer_len`, you can control the pool size, enabling efficient buffer reuse. Frames obtained from the pool should be processed immediately or copied, as references might be invalidated. ```python import rapidshot # Create capture with larger memory pool screencapture = rapidshot.create( output_color="RGB", nvidia_gpu=False, max_buffer_len=64 # Continuous mode buffer size ) # Memory pool is automatically managed internally # Pool size is determined by region size and pool_size_frames parameter # Start high-frequency capture screencapture.start(target_fps=240) frame_count = 0 try: while frame_count < 1000: frame = screencapture.get_latest_frame() if frame is not None: # Frame is from memory pool - avoid holding references # Process immediately or copy if needed frame_copy = frame.copy() if frame_count % 100 == 0 else None frame_count += 1 if frame_copy is not None: print(f"Captured frame {frame_count}: {frame_copy.shape}") except Exception as e: print(f"Error: {e}") finally: screencapture.stop() screencapture.release() print(f"Total frames captured: {frame_count}") ``` -------------------------------- ### Create Screen Capture Instance Source: https://context7.com/zaatra/rapidshot/llms.txt Initialize a screen capture instance for a specific monitor with optional GPU acceleration and color format configuration. Remember to release resources when done. ```APIDOC ## Create Screen Capture Instance ### Description Initialize a screen capture instance for a specific monitor with optional GPU acceleration and color format configuration. ### Method `rapidshot.create()` ### Parameters #### Optional Parameters - **device_idx** (int) - Optional - GPU index (0 for primary). - **output_idx** (int) - Optional - Monitor index (None for primary). - **region** (tuple) - Optional - Capture region (left, top, right, bottom). - **output_color** (str) - Optional - Color format (e.g., "BGR", "RGB"). Defaults to "RGB". - **nvidia_gpu** (bool) - Optional - Enable NVIDIA GPU acceleration. Defaults to False. - **max_buffer_len** (int) - Optional - Buffer size for continuous mode. Defaults to 128. ### Request Example ```python import rapidshot # Basic setup screencapture = rapidshot.create() # Full configuration screencapture = rapidshot.create( device_idx=0, output_idx=0, region=(0, 0, 1920, 1080), output_color="BGR", nvidia_gpu=True, max_buffer_len=128 ) # Multi-monitor setup capture_monitor1 = rapidshot.create(device_idx=0, output_idx=0) capture_monitor2 = rapidshot.create(device_idx=0, output_idx=1) ``` ### Response #### Success Response (Instance Object) - **screencapture** (object) - The initialized screen capture instance. ### Cleanup #### Method `screencapture.release()` ### Description Release resources associated with the screen capture instance. ``` -------------------------------- ### Run RapidShot FPS Benchmark with GPU Acceleration Source: https://github.com/zaatra/rapidshot/blob/main/README.md Shows how to execute RapidShot's maximum frames per second (FPS) benchmark script, including options for enabling GPU acceleration and specifying different color formats for testing. ```bash # Run RapidShot benchmark python benchmarks/rapidshot_max_fps.py # Run with GPU acceleration python benchmarks/rapidshot_max_fps.py --gpu # Test with different color formats python benchmarks/rapidshot_max_fps.py --color BGRA ``` -------------------------------- ### Initialize Screen Capture Instance (Python) Source: https://context7.com/zaatra/rapidshot/llms.txt Initializes a screen capture instance for a specific monitor. Supports configuration for GPU acceleration, output color format, capture region, and buffer length. It's essential to release the instance when done to free up resources. ```python import rapidshot # Basic setup - primary monitor with default settings screencapture = rapidshot.create() # Full configuration with GPU acceleration screencapture = rapidshot.create( device_idx=0, # GPU index (0 for primary) output_idx=0, # Monitor index (None for primary) region=(0, 0, 1920, 1080), # Capture region (left, top, right, bottom) output_color="BGR", # Color format for OpenCV compatibility nvidia_gpu=True, # Enable NVIDIA GPU acceleration max_buffer_len=128 # Buffer size for continuous mode ) # Multi-monitor setup capture_monitor1 = rapidshot.create(device_idx=0, output_idx=0) capture_monitor2 = rapidshot.create(device_idx=0, output_idx=1) # Release resources when done screencapture.release() ``` -------------------------------- ### Configure RapidShot for Multiple Monitors/GPUs Source: https://github.com/zaatra/rapidshot/blob/main/README.md Shows how to initialize RapidShot to capture from specific monitors across different GPUs. It demonstrates printing device information and creating capture instances for individual outputs. ```python # Show available devices and outputs print(rapidshot.device_info()) print(rapidshot.output_info()) # Create ScreenCapture instances for specific devices/outputs capture1 = rapidshot.create(device_idx=0, output_idx=0) # First monitor on first GPU capture2 = rapidshot.create(device_idx=0, output_idx=1) # Second monitor on first GPU capture3 = rapidshot.create(device_idx=1, output_idx=0) # First monitor on second GPU ``` -------------------------------- ### Configure RapidShot Color Formats Source: https://github.com/zaatra/rapidshot/blob/main/README.md Demonstrates initializing RapidShot to capture in different color formats, including RGB, RGBA (with alpha), BGR (compatible with OpenCV), and Grayscale. This is useful for optimizing performance or integrating with other image processing libraries. ```python # RGB (default) screencapture_rgb = rapidshot.create(output_color="RGB") # RGBA (with alpha channel) screencapture_rgba = rapidshot.create(output_color="RGBA") # BGR (OpenCV format) screencapture_bgr = rapidshot.create(output_color="BGR") # Grayscale screencapture_gray = rapidshot.create(output_color="GRAY") ``` -------------------------------- ### Retrieve RapidShot Version and Dependency Information Source: https://context7.com/zaatra/rapidshot/llms.txt This Python script demonstrates how to obtain detailed version information for RapidShot and its dependencies using `rapidshot.get_version_info()`. This is useful for troubleshooting, compatibility checks, and understanding the software environment. ```python import rapidshot import json # Get comprehensive version information version_info = rapidshot.get_version_info() print("RapidShot Configuration:") print(f"Version: {version_info['rapidshot']['version']}") print(f"Description: {version_info['rapidshot']['description']}") print("\nSystem Information:") print(f"Platform: {version_info['system']['platform']}") print(f"Python: {version_info['system']['python']}") print("\nDependency Versions:") for dep, version in version_info['dependencies'].items(): status = "✓" if version != "not installed" else "✗" print(f"{status} {dep}: {version}") # Pretty print as JSON print("\nFull Information:") print(json.dumps(version_info, indent=2)) ``` -------------------------------- ### Cursor Capture Information Source: https://github.com/zaatra/rapidshot/blob/main/README.md Demonstrates how to capture cursor information, including its position and shape, alongside a regular screen capture. The `grab_cursor()` method returns an object with detailed cursor properties. ```python # Take a screenshot frame = screencapture.grab() # Get cursor information cursor = screencapture.grab_cursor() # Check if cursor is visible in the capture area if cursor.PointerPositionInfo.Visible: # Get cursor position x, y = cursor.PointerPositionInfo.Position.x, cursor.PointerPositionInfo.Position.y print(f"Cursor position: ({x}, {y})") # Cursor shape information is also available if cursor.Shape is not None: width = cursor.PointerShapeInfo.Width height = cursor.PointerShapeInfo.Height print(f"Cursor size: {width}x{height}") ``` -------------------------------- ### Set Custom Buffer Size in RapidShot Source: https://github.com/zaatra/rapidshot/blob/main/README.md Explains how to create a RapidShot ScreenCapture instance with a custom maximum buffer length. This allows for managing memory usage or accommodating specific capture rate requirements. ```python # Create a ScreenCapture instance with a larger frame buffer screencapture = rapidshot.create(max_buffer_len=256) ``` -------------------------------- ### Region-based Capture Source: https://github.com/zaatra/rapidshot/blob/main/README.md Shows how to capture a specific rectangular region of the screen by providing coordinates to the `grab` method. The output is a NumPy array representing the captured frame. ```python # Define a specific region left, top = (1920 - 640) // 2, (1080 - 640) // 2 right, bottom = left + 640, top + 640 region = (left, top, right, bottom) # Capture only this region frame = screencapture.grab(region=region) # 640x640x3 numpy.ndarray ``` -------------------------------- ### Region-Based Screen Capture Source: https://context7.com/zaatra/rapidshot/llms.txt Enables efficient capture of specific rectangular regions of the screen. This snippet shows how to define multiple regions of interest and capture frames from each, as well as how to perform continuous capture within a fixed region with a specified frame rate. It includes basic frame rate calculation. ```python import rapidshot import time screencapture = rapidshot.create(output_color="BGR") # Define regions of interest regions = { "top_left": (0, 0, 640, 480), "center": (640, 300, 1280, 780), "bottom_right": (1280, 600, 1920, 1080) } # Capture different regions for name, region in regions.items(): frame = screencapture.grab(region=region) if frame is not None: height, width = frame.shape[:2] print(f"{name}: {width}x{height}") # Continuous capture with fixed region game_region = (100, 100, 900, 700) screencapture.start(target_fps=144, video_mode=False) start_time = time.time() frame_count = 0 while time.time() - start_time < 5: # Run for 5 seconds frame = screencapture.get_latest_frame() if frame is not None: frame_count += 1 fps = frame_count / 5.0 print(f"Average FPS: {fps:.2f}") screencapture.stop() screencapture.release() ``` -------------------------------- ### Manage RapidShot Resources Source: https://github.com/zaatra/rapidshot/blob/main/README.md Provides methods for releasing resources held by RapidShot instances, including explicit release, automatic release upon object deletion, and library-wide cleanup or reset operations. Proper resource management prevents memory leaks and ensures stability. ```python # Release resources when done screencapture.release() # Or automatically released when object is deleted del screencapture # Clean up all resources rapidshot.clean_up() # Reset the library completely rapidshot.reset() ``` -------------------------------- ### Track Cursor Movements with RapidShot Source: https://github.com/zaatra/rapidshot/blob/main/README.md Records cursor positions over a period of time to enable analysis of cursor movements. The code captures timestamped coordinates at a specified interval. ```python import time # Record cursor positions over time positions = [] screencapture = rapidshot.create() for i in range(100): cursor = screencapture.grab_cursor() if cursor.PointerPositionInfo.Visible: positions.append(( time.time(), cursor.PointerPositionInfo.Position.x, cursor.PointerPositionInfo.Position.y )) time.sleep(0.05) # Sample at 20Hz # Analyze cursor movement # ... ``` -------------------------------- ### Screen Capture in Various Color Formats Source: https://context7.com/zaatra/rapidshot/llms.txt Illustrates how to capture screen frames in different color formats, including RGB, BGR, RGBA, and Grayscale. This is crucial for compatibility with various image processing libraries like OpenCV (BGR) and for specific processing needs (Grayscale, RGBA). It shows the shape of the resulting NumPy arrays for each format. ```python import rapidshot import cv2 import numpy as np # RGB format (default) - suitable for PIL, matplotlib capture_rgb = rapidshot.create(output_color="RGB") frame_rgb = capture_rgb.grab() print(f"RGB shape: {frame_rgb.shape}") # (1080, 1920, 3) # BGR format - compatible with OpenCV capture_bgr = rapidshot.create(output_color="BGR") frame_bgr = capture_bgr.grab() cv2.imwrite("opencv_output.png", frame_bgr) # RGBA format - includes alpha channel capture_rgba = rapidshot.create(output_color="RGBA") frame_rgba = capture_rgba.grab() print(f"RGBA shape: {frame_rgba.shape}") # (1080, 1920, 4) # Grayscale format - single channel capture_gray = rapidshot.create(output_color="GRAY") frame_gray = capture_gray.grab() print(f"Grayscale shape: {frame_gray.shape}") # (1080, 1920, 1) ``` -------------------------------- ### Overlay Cursor on Captured Image with RapidShot Source: https://github.com/zaatra/rapidshot/blob/main/README.md Demonstrates how to overlay cursor information onto a captured video frame using RapidShot. This function handles different cursor shape types and ensures the cursor is positioned correctly within the frame boundaries before blending. ```python import numpy as np import cv2 def overlay_cursor(frame, cursor): """Overlay cursor on captured frame.""" if not cursor.PointerPositionInfo.Visible or cursor.Shape is None: return frame # Create an overlay from cursor shape data shape_type = cursor.PointerShapeInfo.Type width = cursor.PointerShapeInfo.Width height = cursor.PointerShapeInfo.Height # Different processing based on cursor type (monochrome, color, or masked) if shape_type & DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MONOCHROME: # Process monochrome cursor # ... elif shape_type & DXGI_OUTDUPL_POINTER_SHAPE_TYPE_COLOR: # Process color cursor # ... elif shape_type & DXGI_OUTDUPL_POINTER_SHAPE_TYPE_MASKED_COLOR: # Process masked color cursor # ... # Position the cursor on the frame at its current coordinates x, y = cursor.PointerPositionInfo.Position.x, cursor.PointerPositionInfo.Position.y # Ensure cursor is within frame boundaries # ... # Blend cursor with frame # ... return frame_with_cursor # Usage example frame = screencapture.grab() cursor = screencapture.grab_cursor() composite_image = overlay_cursor(frame, cursor) ``` -------------------------------- ### Video Recording Source: https://context7.com/zaatra/rapidshot/llms.txt Record screen activity to a video file using OpenCV's VideoWriter, leveraging the continuous capture mode. Ensure the output color format is compatible with OpenCV (e.g., BGR). ```APIDOC ## Video Recording ### Description Record screen activity to a video file using OpenCV's VideoWriter with continuous capture mode. ### Setup 1. **Create Capture Instance**: Initialize `rapidshot` with an `output_color` compatible with OpenCV (e.g., "BGR"). 2. **Configure Video Writer**: Use `cv2.VideoWriter` specifying the output filename, codec, frame rate, and resolution. 3. **Start Capture**: Call `screencapture.start()` with `video_mode=True`. 4. **Record Frames**: In a loop, get the latest frame using `screencapture.get_latest_frame()` and write it using `writer.write()`. 5. **Stop and Release**: Call `screencapture.stop()`, `writer.release()`, and `screencapture.release()`. ### Request Example ```python import rapidshot import cv2 # Create capture instance with BGR format for OpenCV screencapture = rapidshot.create(output_color="BGR") # Configure video writer width, height = 1920, 1080 # Example resolution fourcc = cv2.VideoWriter_fourcc(*"mp4v") # Codec for MP4 fps = 30 writer = cv2.VideoWriter("recording.mp4", fourcc, fps, (width, height)) # Start capturing in video mode screencapture.start(target_fps=fps, video_mode=True) try: # Record for a specific duration or number of frames num_frames_to_record = 300 # e.g., 10 seconds at 30 FPS for i in range(num_frames_to_record): frame = screencapture.get_latest_frame() if frame is not None: writer.write(frame) print(f"Recorded frame {i+1}/{num_frames_to_record}") except Exception as e: print(f"Error during recording: {e}") finally: screencapture.stop() writer.release() screencapture.release() print("Video saved successfully") ``` ### Response No direct API response. The output is a video file (e.g., `recording.mp4`). ### Cleanup #### Methods - `screencapture.stop()` - `writer.release()` - `screencapture.release()` ### Description Stop the capture thread, release the video writer, and release the screen capture instance resources. ``` -------------------------------- ### Capture Mouse Cursor Information Source: https://context7.com/zaatra/rapidshot/llms.txt Shows how to capture the mouse cursor's position, visibility, and shape alongside screen content. It explains how to access cursor visibility, coordinates, dimensions, type, and the raw shape buffer. This functionality helps in applications that need to track or manipulate the cursor. ```python import rapidshot screencapture = rapidshot.create() # Capture frame and cursor simultaneously frame = screencapture.grab() cusor = screencapture.grab_cursor() # Check cursor visibility and position if cursor.PointerPositionInfo.Visible: x = cursor.PointerPositionInfo.Position.x y = cursor.PointerPositionInfo.Position.y print(f"Cursor position: ({x}, {y})") # Access cursor shape information if cursor.Shape is not None: width = cursor.PointerShapeInfo.Width height = cursor.PointerShapeInfo.Height shape_type = cursor.PointerShapeInfo.Type print(f"Cursor size: {width}x{height}, Type: {shape_type}") # Shape buffer contains cursor bitmap data shape_buffer = cursor.Shape print(f"Shape buffer size: {len(shape_buffer)} bytes") else: print("Cursor not visible") screencapture.release() ``` -------------------------------- ### Continuous Frame Capture (Python) Source: https://context7.com/zaatra/rapidshot/llms.txt Enables continuous screen frame capturing in a background thread, suitable for real-time applications. Frames are captured at a target frames per second. `get_latest_frame()` retrieves the most recent frame. Stop the capture and release resources when finished. ```python import rapidshot import time screencapture = rapidshot.create(output_color="RGB") # Start capturing at 60 FPS screencapture.start(target_fps=60, video_mode=False) try: for i in range(300): # Capture 300 frames frame = screencapture.get_latest_frame() if frame is not None: # Process frame (e.g., object detection, analysis) print(f"Frame {i}: {frame.shape}") time.sleep(0.001) # Minimal delay for processing except KeyboardInterrupt: print("Capture interrupted") finally: screencapture.stop() screencapture.release() ``` -------------------------------- ### Record Screen to Video (Python with OpenCV) Source: https://context7.com/zaatra/rapidshot/llms.txt Records screen activity to a video file using OpenCV's VideoWriter. This function leverages the continuous capture mode and requires the output color format to be BGR for compatibility with OpenCV. Ensure to stop the capture and release both the capture instance and the video writer. ```python import rapidshot import cv2 # Create capture instance with BGR format for OpenCV screencapture = rapidshot.create(output_color="BGR") # Configure video writer fourcc = cv2.VideoWriter_fourcc(*"mp4v") writer = cv2.VideoWriter("recording.mp4", fourcc, 30, (1920, 1080)) # Start capturing in video mode (duplicates last frame if no update) screencapture.start(target_fps=30, video_mode=True) try: # Record for 10 seconds (300 frames at 30 FPS) for i in range(300): frame = screencapture.get_latest_frame() if frame is not None: writer.write(frame) print(f"Recorded frame {i+1}/300") except Exception as e: print(f"Error during recording: {e}") finally: screencapture.stop() writer.release() screencapture.release() print("Video saved successfully") ``` -------------------------------- ### Single Frame Capture Source: https://context7.com/zaatra/rapidshot/llms.txt Capture a single screenshot from the display as a NumPy array. You can specify a region to capture a portion of the screen. ```APIDOC ## Single Frame Capture ### Description Capture a single screenshot from the display as a NumPy array, with optional region specification. ### Method `screencapture.grab(region=None)` ### Parameters #### Optional Parameters - **region** (tuple) - Optional - Capture region (left, top, right, bottom). If None, captures the full screen. ### Request Example ```python import rapidshot from PIL import Image screencapture = rapidshot.create(output_color="RGB") # Capture full screen frame = screencapture.grab() if frame is not None: print(f"Captured frame shape: {frame.shape}") # (1080, 1920, 3) Image.fromarray(frame).save("screenshot.png") # Capture specific region (center 640x640) left, top = (1920 - 640) // 2, (1080 - 640) // 2 region = (left, top, left + 640, top + 640) frame_region = screencapture.grab(region=region) print(f"Region shape: {frame_region.shape}") # (640, 640, 3) ``` ### Response #### Success Response (200) - **frame** (numpy.ndarray) - A NumPy array representing the captured image. Returns None if capture fails. ### Cleanup #### Method `screencapture.release()` ### Description Release resources associated with the screen capture instance. ``` -------------------------------- ### Capture Single Screenshot (Python) Source: https://context7.com/zaatra/rapidshot/llms.txt Captures a single screenshot from the display. It can capture the full screen or a specified region, returning the frame as a NumPy array. The output color format can be configured for compatibility with libraries like OpenCV. Ensure the capture instance is released after use. ```python import rapidshot from PIL import Image screencapture = rapidshot.create(output_color="RGB") # Capture full screen frame = screencapture.grab() if frame is not None: print(f"Captured frame shape: {frame.shape}") # (1080, 1920, 3) Image.fromarray(frame).save("screenshot.png") # Capture specific region (center 640x640) left, top = (1920 - 640) // 2, (1080 - 640) // 2 region = (left, top, left + 640, top + 640) frame_region = screencapture.grab(region=region) print(f"Region shape: {frame_region.shape}") # (640, 640, 3) screencapture.release() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.