### Build pyvirtualcam from source Source: https://github.com/letmaik/pyvirtualcam/blob/main/README.md Instructions for cloning the repository and installing the package from source on Unix-like systems. ```bash git clone https://github.com/letmaik/pyvirtualcam --recursive cd pyvirtualcam pip install . ``` -------------------------------- ### Create and Initialize a Virtual Camera in Python Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Demonstrates how to create a virtual camera instance with specified dimensions and FPS. It initializes a camera with default RGB format and prints its configuration. The example also shows how to create a solid color frame and send it to the virtual camera. ```python import numpy as np import pyvirtualcam # Create a virtual camera with RGB format (default) with pyvirtualcam.Camera(width=1280, height=720, fps=20) as cam: print(f'Using virtual camera: {cam.device}') print(f'Backend: {cam.backend}') print(f'Resolution: {cam.width}x{cam.height}') print(f'Target FPS: {cam.fps}') # Create a red frame frame = np.zeros((cam.height, cam.width, 3), np.uint8) frame[:, :] = [255, 0, 0] # RGB red # Send frame to virtual camera cam.send(frame) ``` -------------------------------- ### Install pyvirtualcam via pip Source: https://github.com/letmaik/pyvirtualcam/blob/main/README.md Standard command to install the pyvirtualcam package from PyPI. ```bash pip install pyvirtualcam ``` -------------------------------- ### Configure v4l2loopback on Linux Source: https://github.com/letmaik/pyvirtualcam/blob/main/README.md Commands to install and load the v4l2loopback kernel module required for virtual cameras on Linux systems. ```bash sudo apt install v4l2loopback-dkms sudo modprobe v4l2loopback devices=1 ``` -------------------------------- ### Adaptive Frame Timing with sleep_until_next_frame() in Python Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Shows how to use sleep_until_next_frame() for adaptive frame timing to maintain a consistent FPS. The example cycles through red, green, and blue frames, sending each frame and then sleeping until the next frame is due. ```python import time import numpy as np import pyvirtualcam colors = [ ('RED', np.array([255, 0, 0], np.uint8)), ('GREEN', np.array([0, 255, 0], np.uint8)), ('BLUE', np.array([0, 0, 255], np.uint8)) ] with pyvirtualcam.Camera(width=1280, height=720, fps=30, print_fps=True) as cam: print(f'Using virtual camera: {cam.device}') frame = np.zeros((cam.height, cam.width, 3), np.uint8) t_last_change = 0 color_idx = 0 while True: t_now = time.time() if t_now - t_last_change >= 1: t_last_change = t_now color_idx = (color_idx + 1) % len(colors) name, color = colors[color_idx] print(name) frame[:, :] = color cam.send(frame) # Adaptive sleep maintains consistent FPS cam.sleep_until_next_frame() ``` -------------------------------- ### Stream Animated GIF with Transparency to Virtual Camera (Python) Source: https://context7.com/letmaik/pyvirtualcam/llms.txt This example shows how to load an animated GIF with transparency and stream it to a virtual camera using pyvirtualcam with the RGBA pixel format. It centers the GIF on a transparent background within the virtual camera frame. This requires a backend that supports RGBA, such as Unity Capture on Windows. ```python import numpy as np import imageio import pyvirtualcam from pyvirtualcam import PixelFormat # Load animated GIF with transparency gif = imageio.get_reader("animation.gif") gif_length = gif.get_length() gif_height, gif_width = gif.get_data(0).shape[:2] gif_fps = 1000 / gif.get_meta_data()['duration'] cam_width = 1280 cam_height = 720 # Center the GIF on the frame gif_x = (cam_width - gif_width) // 2 gif_y = (cam_height - gif_height) // 2 # Use RGBA format for transparency with pyvirtualcam.Camera(cam_width, cam_height, gif_fps, fmt=PixelFormat.RGBA, print_fps=True) as cam: print(f'Virtual cam started: {cam.device}') count = 0 frame = np.zeros((cam.height, cam.width, 4), np.uint8) # RGBA while True: if count == gif_length: count = 0 gif_frame = gif.get_data(count) # Clear frame (transparent background) frame[:] = 0 # Place GIF frame in center frame[gif_y:gif_y+gif_height, gif_x:gif_x+gif_width] = gif_frame cam.send(frame) cam.sleep_until_next_frame() count += 1 ``` -------------------------------- ### Select Specific Virtual Camera Device (Python) Source: https://context7.com/letmaik/pyvirtualcam/llms.txt This snippet demonstrates how to select a specific virtual camera device by name or path using the `device` parameter in pyvirtualcam. This is useful when multiple virtual cameras are present on the system. It includes examples for Linux, Windows/macOS OBS, and Windows Unity Capture. ```python import numpy as np import pyvirtualcam from pyvirtualcam import PixelFormat # Linux: Specify device path # device = "/dev/video2" # Windows/macOS OBS: Use device name # device = "OBS Virtual Camera" # Windows Unity Capture: Use device name device = "Unity Video Capture" try: with pyvirtualcam.Camera( width=1280, height=720, fps=30, fmt=PixelFormat.RGBA, device=device, print_fps=True ) as cam: print(f'Using device: {cam.device}') print(f'Backend: {cam.backend}') frame = np.zeros((cam.height, cam.width, 4), np.uint8) frame[:, :] = [255, 0, 0, 255] # Opaque red while True: cam.send(frame) cam.sleep_until_next_frame() except RuntimeError as e: print(f"Failed to open camera: {e}") ``` -------------------------------- ### Send Frames to Virtual Camera with send() in Python Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Illustrates the use of the send() method to transmit numpy array frames to a virtual camera. This example creates a frame with cycling hue colors and continuously sends it to the camera, maintaining the target frame rate. ```python import colorsys import numpy as np import pyvirtualcam with pyvirtualcam.Camera(width=1280, height=720, fps=20, print_fps=True) as cam: print(f'Using virtual camera: {cam.device}') frame = np.zeros((cam.height, cam.width, 3), np.uint8) # RGB while True: # Create cycling hue colors h, s, v = (cam.frames_sent % 100) / 100, 1.0, 1.0 r, g, b = colorsys.hsv_to_rgb(h, s, v) frame[:] = (r * 255, g * 255, b * 255) # Send frame to virtual camera cam.send(frame) # Maintain target frame rate cam.sleep_until_next_frame() ``` -------------------------------- ### Use BGR Pixel Format with OpenCV and pyvirtualcam in Python Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Demonstrates how to configure pyvirtualcam to use the BGR pixel format, which is compatible with OpenCV's default color ordering. This example reads frames from a video file and streams them to the virtual camera without color conversion. ```python import cv2 import pyvirtualcam from pyvirtualcam import PixelFormat # Open video file video = cv2.VideoCapture("video.mp4") if not video.isOpened(): raise ValueError("Error opening video") width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = video.get(cv2.CAP_PROP_FPS) length = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) # Use BGR format to match OpenCV's default with pyvirtualcam.Camera(width, height, fps, fmt=PixelFormat.BGR, print_fps=True) as cam: print(f'Virtual cam started: {cam.device} ({cam.width}x{cam.height} @ {cam.fps}fps)') count = 0 while True: # Restart video on last frame if count == length: count = 0 video.set(cv2.CAP_PROP_POS_FRAMES, 0) ret, frame = video.read() if not ret: raise RuntimeError('Error fetching frame') # Send BGR frame directly (no conversion needed) cam.send(frame) cam.sleep_until_next_frame() count += 1 ``` -------------------------------- ### Stream frames to a virtual camera in Python Source: https://github.com/letmaik/pyvirtualcam/blob/main/README.md Demonstrates how to initialize a virtual camera instance and stream RGB frames generated from HSV color values in a loop. ```python import colorsys import numpy as np import pyvirtualcam with pyvirtualcam.Camera(width=1280, height=720, fps=20) as cam: print(f'Using virtual camera: {cam.device}') frame = np.zeros((cam.height, cam.width, 3), np.uint8) # RGB while True: h, s, v = (cam.frames_sent % 100) / 100, 1.0, 1.0 r, g, b = colorsys.hsv_to_rgb(h, s, v) frame[:] = (r * 255, g * 255, b * 255) cam.send(frame) cam.sleep_until_next_frame() ``` -------------------------------- ### Accessing Camera Configuration and Runtime Properties Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Shows how to inspect camera settings such as dimensions, pixel format, and backend information, as well as tracking runtime metrics like frames sent and current FPS. ```python import numpy as np import pyvirtualcam from pyvirtualcam import PixelFormat with pyvirtualcam.Camera(width=1920, height=1080, fps=30, fmt=PixelFormat.BGR, print_fps=True) as cam: print(f"Width: {cam.width}") print(f"Height: {cam.height}") print(f"Target FPS: {cam.fps}") print(f"Format: {cam.fmt}") print(f"Native format: {cam.native_fmt}") print(f"Device: {cam.device}") print(f"Backend: {cam.backend}") frame = np.zeros((cam.height, cam.width, 3), np.uint8) for i in range(100): frame[:] = [i * 2, 100, 255 - i * 2] cam.send(frame) cam.sleep_until_next_frame() print(f"Frames sent: {cam.frames_sent}") print(f"Current FPS: {cam.current_fps:.1f}") ``` -------------------------------- ### Camera Initialization and Stream Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Initializes a virtual camera instance to stream frames from a source, such as a physical webcam or custom processing pipeline. ```APIDOC ## POST /pyvirtualcam/Camera ### Description Initializes a new virtual camera device with specific dimensions, frame rate, and pixel format. ### Method POST ### Endpoint pyvirtualcam.Camera(width, height, fps, fmt, device=None) ### Parameters #### Path Parameters - **width** (int) - Required - Frame width in pixels - **height** (int) - Required - Frame height in pixels - **fps** (int) - Required - Frames per second - **fmt** (PixelFormat) - Required - Pixel format (e.g., BGR, RGBA) - **device** (str) - Optional - Specific device name or path ### Request Example with pyvirtualcam.Camera(1280, 720, fps=30, fmt=PixelFormat.BGR) as cam: ### Response #### Success Response (200) - **cam** (object) - Active camera instance ``` -------------------------------- ### Implementing the Backend Abstract Interface Source: https://github.com/letmaik/pyvirtualcam/blob/main/docs/index.md Provides a template for implementing the required methods for a custom backend. The interface requires handling frame data, device lifecycle, and pixel format reporting. ```python class BackendInterface: def __init__(self, width, height, fps, fourcc, device=None, **kw): """Initialize the backend with camera parameters.""" raise NotImplementedError def send(self, frame): """Send a 1D C-contiguous uint8 numpy array to the device.""" raise NotImplementedError def close(self): """Release resources associated with the device.""" raise NotImplementedError def device(self): """Return the name of the virtual camera device in use.""" raise NotImplementedError def native_fourcc(self): """Return the native libyuv FourCC code.""" raise NotImplementedError ``` -------------------------------- ### Build pyvirtualcam on Windows Source: https://github.com/letmaik/pyvirtualcam/blob/main/README.md Experimental PowerShell script to build the project on Windows using environment variables to configure the build environment. ```powershell $env:USE_CONDA = '1' $env:PYTHON_VERSION = '3.7' $env:PYTHON_ARCH = '64' $env:NUMPY_VERSION = '1.14' git clone https://github.com/letmaik/pyvirtualcam --recursive cd pyvirtualcam powershell .github/scripts/build-windows.ps1 ``` -------------------------------- ### Capture Webcam, Apply Filter, Output to Virtual Camera (Python) Source: https://context7.com/letmaik/pyvirtualcam/llms.txt This snippet demonstrates capturing video from a webcam using OpenCV, applying a simple shake filter, and streaming the processed frames to a virtual camera using pyvirtualcam. It configures both the real webcam and the virtual camera, handling frame reading and sending. ```python import cv2 import pyvirtualcam from pyvirtualcam import PixelFormat # Set up webcam capture vc = cv2.VideoCapture(0) # Camera device ID if not vc.isOpened(): raise RuntimeError('Could not open video source') # Configure capture settings vc.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) vc.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) vc.set(cv2.CAP_PROP_FPS, 30) # Query actual capture settings width = int(vc.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT)) print(f'Webcam capture started ({width}x{height})') with pyvirtualcam.Camera(width, height, fps=20, fmt=PixelFormat.BGR, print_fps=True) as cam: print(f'Virtual cam started: {cam.device}') channels = [[0, 1], [0, 2], [1, 2]] while True: ret, frame = vc.read() if not ret: raise RuntimeError('Error fetching frame') # Apply shake filter effect dx = 15 - cam.frames_sent % 5 c1, c2 = channels[cam.frames_sent % 3] frame[:, :-dx, c1] = frame[:, dx:, c1] frame[:, dx:, c2] = frame[:, :-dx, c2] cam.send(frame) cam.sleep_until_next_frame() ``` -------------------------------- ### Registering a Custom Backend in pyvirtualcam Source: https://github.com/letmaik/pyvirtualcam/blob/main/docs/index.md Demonstrates how to register a custom backend class with the pyvirtualcam library. The register_backend function associates a unique name with a backend class implementation. ```python import pyvirtualcam class MyCustomBackend: def __init__(self, width, height, fps, fourcc, device=None, **kw): pass def send(self, frame): pass def close(self): pass def device(self): return "MyDevice" def native_fourcc(self): return None # Register the backend pyvirtualcam.register_backend("my_backend", MyCustomBackend) ``` -------------------------------- ### pyvirtualcam.Camera Class Source: https://github.com/letmaik/pyvirtualcam/blob/main/docs/index.md The main class for initializing and controlling a virtual camera device. ```APIDOC ## CLASS pyvirtualcam.Camera ### Description Initializes a virtual camera instance to stream frames to a system device. ### Parameters - **width** (int) - Required - Frame width in pixels. - **height** (int) - Required - Frame height in pixels. - **fps** (float) - Required - Target frame rate. - **fmt** (PixelFormat) - Optional - Input pixel format (default: RGB). - **device** (str) - Optional - Name of the virtual camera device. - **backend** (str) - Optional - Backend to use (v4l2loopback, obs, unitycapture). - **print_fps** (bool) - Optional - Print FPS every second. ### Methods - **send(frame)**: Sends a numpy.ndarray frame to the camera. - **sleep_until_next_frame()**: Adaptive sleep to maintain target FPS. - **close()**: Frees device resources. ``` -------------------------------- ### register_backend Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Registers a custom backend class that conforms to the Backend interface for use with the Camera context. ```APIDOC ## FUNCTION register_backend ### Description Registers a custom class as a virtual camera backend. The class must implement the Backend interface including __init__, close, send, device, and native_fourcc methods. ### Method Python Function Call ### Parameters #### Arguments - **name** (str) - Required - The unique name identifier for the backend. - **backend_class** (class) - Required - The class implementing the Backend interface. ### Request Example register_backend('custom', CustomBackend) ### Response #### Success Response - **None** (void) - Returns nothing upon successful registration. ``` -------------------------------- ### Camera Properties Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Accessing configuration and runtime state properties of an active Camera instance. ```APIDOC ## CLASS Camera Properties ### Description Provides access to configuration settings (width, height, fps, format) and runtime metrics (frames_sent, current_fps) of the virtual camera. ### Method Property Access ### Parameters #### Instance Properties - **width** (int) - Read-only - Frame width in pixels. - **height** (int) - Read-only - Frame height in pixels. - **fps** (float) - Read-only - Target frame rate. - **frames_sent** (int) - Read-only - Total frames sent to the device. - **current_fps** (float) - Read-only - Measured frame rate. ### Response Example { "width": 1920, "height": 1080, "fps": 30, "frames_sent": 100, "current_fps": 29.9 } ``` -------------------------------- ### Understanding pyvirtualcam PixelFormat Enum (Python) Source: https://context7.com/letmaik/pyvirtualcam/llms.txt This code snippet illustrates the different pixel formats supported by pyvirtualcam using the `PixelFormat` enum. It shows the expected NumPy array shapes for common formats like RGB, BGR, RGBA, GRAY, and various YUV formats (I420, NV12, YUYV, UYVY). It also prints all available formats and their values. ```python from pyvirtualcam import PixelFormat import numpy as np width, height = 1280, 720 # RGB: Shape (h, w, 3) rgb_frame = np.zeros((height, width, 3), np.uint8) # BGR: Shape (h, w, 3) - OpenCV default bgr_frame = np.zeros((height, width, 3), np.uint8) # RGBA: Shape (h, w, 4) - with alpha channel rgba_frame = np.zeros((height, width, 4), np.uint8) # GRAY: Shape (h, w) - grayscale gray_frame = np.zeros((height, width), np.uint8) # I420: Size w * h * 3/2 - YUV planar format i420_frame = np.zeros(width * height * 3 // 2, np.uint8) # NV12: Size w * h * 3/2 - YUV semi-planar format nv12_frame = np.zeros(width * height * 3 // 2, np.uint8) # YUYV: Size w * h * 2 - packed YUV format yuyv_frame = np.zeros(width * height * 2, np.uint8) # UYVY: Size w * h * 2 - packed YUV format uyvy_frame = np.zeros(width * height * 2, np.uint8) # All available formats print("Available pixel formats:") for fmt in PixelFormat: print(f" {fmt.name}: {fmt.value!r}") ``` -------------------------------- ### pyvirtualcam.PixelFormat Enum Source: https://github.com/letmaik/pyvirtualcam/blob/main/docs/index.md Supported pixel formats for frame data. ```APIDOC ## ENUM pyvirtualcam.PixelFormat ### Description Defines the pixel format of the input frames expected by the camera. ### Supported Formats - **RGB**: (h, w, 3) - **BGR**: (h, w, 3) - **RGBA**: (h, w, 4) - **GRAY**: (h, w) - **I420, NV12, UYVY, YUYV**: Various packed formats. ``` -------------------------------- ### Frame Transmission Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Sends image data to the virtual camera and manages timing for consistent frame rates. ```APIDOC ## POST /pyvirtualcam/Camera/send ### Description Sends a single frame to the virtual camera and waits for the next scheduled frame interval. ### Method POST ### Endpoint cam.send(frame) / cam.sleep_until_next_frame() ### Parameters #### Request Body - **frame** (numpy.ndarray) - Required - Image data matching the initialized dimensions and format ### Request Example cam.send(frame) cam.sleep_until_next_frame() ``` -------------------------------- ### PixelFormat Enum Source: https://context7.com/letmaik/pyvirtualcam/llms.txt Defines the supported pixel formats and their corresponding memory layouts for frame buffers. ```APIDOC ## GET /pyvirtualcam/PixelFormat ### Description Lists the supported pixel formats used for configuring the camera output. ### Method GET ### Endpoint pyvirtualcam.PixelFormat ### Response #### Success Response (200) - **RGB** (int) - 3-channel interleaved - **BGR** (int) - 3-channel interleaved (OpenCV default) - **RGBA** (int) - 4-channel with alpha transparency - **GRAY** (int) - Single channel grayscale - **I420/NV12/YUYV/UYVY** (int) - Various YUV planar and packed formats ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.