### Quick Start Docker Commands for VidGear Reference Implementation Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md These commands demonstrate how to build and run a Docker container for the VidGear reference implementation. They cover building the image, running with basic configuration, using docker-compose for more complex setups, and managing the container lifecycle. ```bash docker build -t my-vidgear-app . docker run -v "$(pwd)/output:/app/output" \ -e VIDEO_URL="https://youtu.be/dQw4w9WgXcQ" \ my-vidgear-app docker-compose up docker-compose up -d docker-compose logs -f docker-compose down docker-compose up --build ``` -------------------------------- ### Dockerfile for OpenCV and VidGear Setup Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md This Dockerfile sets up a build environment for OpenCV with video support and then creates a lean runtime image. It installs system dependencies, downloads and installs pre-built OpenCV, and then installs VidGear. ```docker # Stage 1: Build OpenCV with full video support # Supported Linux Distributions: Ubuntu 22.04 (4) FROM ubuntu:22.04 AS opencv-installer ENV DEBIAN_FRONTEND=noninteractive # Install runtime dependencies first RUN apt-get update && apt-get install -y \ python3 python3-pip curl \ # FFmpeg and codecs ffmpeg libavcodec58 libavformat-dev libavutil-dev \ libswscale-dev libswresample-dev \ libx264-dev libxvidcore-dev \ # GStreamer libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \ gstreamer1.0-plugins-good gstreamer1.0-plugins-bad \ gstreamer1.0-plugins-ugly gstreamer1.0-libav \ # Image libraries libjpeg-dev libpng-dev libtiff-dev libwebp-dev \ # Math libraries libatlas-base-dev libopenblas-dev \ && rm -rf /var/lib/apt/lists/* # Download and install pre-built OpenCV with GStreamer support (1) RUN PYTHONSUFFIX=$(python3 -c 'import sys; print(".".join(map(str, sys.version_info[:2])))") && \ echo "Detecting Python $PYTHONSUFFIX" && \ LATEST_VERSION=$(curl -sL https://api.github.com/repos/abhiTronix/OpenCV-CI-Releases/releases/latest | \ grep "OpenCV-.*-$PYTHONSUFFIX.*.deb" | \ grep -Eo "(http|https)://[a-zA-Z0-9./?=_%:-]*" | head -1) && \ echo "Downloading: $LATEST_VERSION" && \ curl -LO $LATEST_VERSION && \ OPENCV_FILENAME=$(basename "$LATEST_VERSION") && \ python3 -m pip install numpy && \ dpkg -i "$OPENCV_FILENAME" && \ # Link OpenCV to Python dist-packages ln -sf /usr/local/lib/python$PYTHONSUFFIX/site-packages/*.so /usr/lib/python3/dist-packages/ && \ ldconfig && \ # Verify installation python3 -c "import cv2; print(f'OpenCV {cv2.__version__} installed')" # Stage 2: Runtime image # Supported Linux Distributions: Ubuntu 22.04 FROM ubuntu:22.04 ENV DEBIAN_FRONTEND=noninteractive # Install ONLY runtime dependencies (no build tools) RUN apt-get update && apt-get install -y \ python3 python3-pip \ ffmpeg \ libavcodec-dev libavformat-dev libavutil-dev \ libswscale-dev libswresample-dev \ gstreamer1.0-tools gstreamer1.0-plugins-good \ gstreamer1.0-plugins-bad gstreamer1.0-plugins-ugly \ gstreamer1.0-libav \ libatlas-base-dev libopenblas-dev \ && rm -rf /var/lib/apt/lists/* # Copy OpenCV from builder COPY --from=opencv-installer /usr/local/lib/ /usr/local/lib/ COPY --from=opencv-installer /usr/local/include/ /usr/local/include/ COPY --from=opencv-installer /usr/lib/python3/dist-packages/ /usr/lib/python3/dist-packages/ # Update library cache RUN ldconfig WORKDIR /app # Install VidGear and dependencies (2) COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # Verify everything works (3) RUN python3 -c "import cv2; print('OpenCV:', cv2.__version__, '| GStreamer:', cv2.videoio_registry.getBackendName(cv2.CAP_GSTREAMER))" && \ python3 -c "import vidgear; print('VidGear:', vidgear.__version__)" && \ ffmpeg -version | head -n 1 # Security: non-root user (5) RUN useradd -r -m -u 1000 vidgear && \ mkdir -p /app/output && \ chown -R vidgear:vidgear /app COPY app/ ./app/ RUN chown -R vidgear:vidgear /app USER vidgear CMD ["python3", "-m", "app.streamer"] ``` -------------------------------- ### Adjust PiCamera Brightness at Runtime Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/pigear_ex.md This example shows how to set the initial brightness and dynamically change it during runtime by pressing a key. Ensure the PiGear library is installed and a compatible camera is connected. ```python # import required libraries from vidgear.gears import PiGear import cv2 # formulate initial configurational parameters # set brightness to `80` (bright) options = {"brightness": 80} # open pi video stream with these parameters stream = PiGear(logging=True, **options).start() # loop over while True: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # Show output window cv2.imshow("Output Frame", frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # check for 'z' key if pressed if key == ord("z"): # change brightness to `30` (darker) stream.stream.brightness = 30 # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### NetGear_Async Server Setup Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/usage.md This snippet shows the basic server-side setup for NetGear_Async. Ensure the source path is valid and logging is enabled for debugging. ```python # import libraries from vidgear.gears.asyncio import NetGear_Async import asyncio # initialize Server with suitable source server = NetGear_Async(source="/home/foo/foo1.mp4").launch() if __name__ == "__main__": # set event loop asyncio.set_event_loop(server.loop) try: # run your main function task until it is complete server.loop.run_until_complete(server.task) except (KeyboardInterrupt, SystemExit): # wait for interrupts pass finally: # finally close the server server.close() ``` -------------------------------- ### Windows Installation with `python -m pip` Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md On Windows, preface Python commands with `python -m` for installation. This installs VidGear with core or core and asyncio dependencies. ```sh python -m pip install -U vidgear[core] ``` ```sh python -m pip install -U vidgear[asyncio] ``` -------------------------------- ### Bare-Minimum Source Install Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/source_install.md Clone the repository and install VidGear with bare-minimum dependencies, followed by installing critical and API-specific dependencies separately. ```sh # clone the repository and get inside git clone https://github.com/abhiTronix/vidgear.git && cd vidgear # checkout the latest testing branch git checkout testing # Install stable release with bare-minimum dependencies pip install . ``` ```sh # Install opencv(only if not installed previously) pip install opencv-python ``` ```sh # Just copy-&-paste from table below pip install ``` -------------------------------- ### Using ScreenGear with MSS Backend Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/screengear/usage.md This example demonstrates opening a video stream with the ScreenGear API using the `mss` backend for frame extraction. Ensure the `mss` library and its dependencies are installed. The `logging` parameter is enabled for debugging. ```python # import required libraries from vidgear.gears import ScreenGear import cv2 # open video stream with defined parameters and `mss` backend # for extracting frames. stream = ScreenGear(backend="mss", logging=True).start() # loop over while True: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # Show output window cv2.imshow("Output Frame", frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### Install Uvloop for NetGear_Async Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Install the `uvloop` library for enhanced performance with the `NetGear_Async` API on UNIX-like systems. Note: Not supported on Windows. ```sh pip install uvloop ``` -------------------------------- ### Install v4l2loopback module Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/writegear_ex.md Commands to install the v4l2loopback module and create a virtual camera device. ```sh sudo apt-get install v4l2loopback-dkms v4l2loopback-utils linux-modules-extra-$(uname -r) sudo modprobe v4l2loopback devices=1 video_nr=0 exclusive_caps=1 card_label='VCamera' ``` -------------------------------- ### Install DXcam for Windows Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/screengear/usage.md On Windows, install the 'dxcam' library via pip for higher FPS performance with ScreenGear. ```sh pip install dxcam ``` -------------------------------- ### Install VidGear from Source with Extras Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/poetry_install.md Clone the VidGear repository and install it into your Poetry environment, including specified extras like 'core' or 'asyncio'. ```sh git clone https://github.com/abhiTronix/vidgear.git && cd vidgear ``` ```sh poetry install --extras core ``` ```sh poetry install --extras asyncio ``` -------------------------------- ### Install Vidgear using pip with Asyncio Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/source_install.md Install the latest stable release with all core and asyncio dependencies directly using pip. ```bash py -m pip install --upgrade --user .[asyncio] ``` -------------------------------- ### Install VidGear from Wheel Package Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Install VidGear by downloading its wheel (`.whl`) package from the releases section and using pip. ```sh pip install vidgear-0.3.4-py3-none-any.whl[core] ``` ```sh pip install vidgear-0.3.4-py3-none-any.whl[asyncio] ``` -------------------------------- ### Install Legacy Picamera Library Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Use this command to install the legacy `picamera` library if your OS does not support Picamera2 or if you need to enforce its use in PiGear. ```sh pip install picamera ``` -------------------------------- ### Clean Install from Source Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/source_install.md Always uninstall prior installations before reinstalling from source, especially when switching branches or performing major refactors to avoid lingering files. ```sh # uninstall any prior install (repeat until "not installed" reported) pip uninstall -y vidgear # then reinstall fresh pip install -U . ``` -------------------------------- ### Bare-Minimum ScreenGear Usage Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/screengear/usage.md This snippet shows the basic setup to start a screen stream, read frames, display them, and stop the stream. It requires 'vidgear' and 'opencv-python' to be installed. ```python # import required libraries from vidgear.gears import ScreenGear import cv2 # open video stream with default parameters stream = ScreenGear().start() # loop over while True: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # Show output window cv2.imshow("Output Frame", frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### Initialize NetGear Async with Video File Path Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/params.md Provide a valid file path to a video file as the source. ```python NetGear_Async(source='/home/foo.mp4') ``` -------------------------------- ### Install Picamera2 without GUI Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Installs Picamera2 on Raspberry Pi OS without GUI dependencies, suitable for headless or minimal setups. ```sh sudo apt install -y python3-picamera2 --no-install-recommends ``` -------------------------------- ### FFGear Source Parameter Examples Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/webgear_rtc/params.md Demonstrates setting the video source for the FFGear backend using a local file or an RTSP stream. ```python from vidgear.gears.helper import Backend WebGear_RTC(api=Backend.FFGEAR, source="myvideo.mp4") WebGear_RTC(api=Backend.FFGEAR, source="rtsp://192.168.1.10:554/stream") ``` -------------------------------- ### Using Stabilizer with WriteGear Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/stabilizer/usage.md This example demonstrates how to use the Stabilizer class with WriteGear to process and save stabilized video frames. Ensure you have the necessary Vidgear libraries installed. ```python # import required libraries from vidgear.gears.stabilizer import Stabilizer from vidgear.gears import CamGear from vidgear.gears import WriteGear import cv2 # Open suitable video stream stream = CamGear(source="unstabilized_stream.mp4").start() # initiate stabilizer object with default parameters stab = Stabilizer() # Define writer with default parameters and suitable output filename for e.g. `Output.mp4` writer = WriteGear(output="Output.mp4") # loop over while True: # read frames from stream frame = stream.read() # check for frame if not None-type if frame is None: break # send current frame to stabilizer for processing stabilized_frame = stab.stabilize(frame) # wait for stabilizer which still be initializing if stabilized_frame is None: continue # {do something with the stabilized frame here} # write stabilized frame to writer writer.write(stabilized_frame) # Show output window cv2.imshow("Stabilized Frame", stabilized_frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # clear stabilizer resources stab.clean() # safely close video stream stream.stop() # safely close writer writer.close() ``` -------------------------------- ### YouTube Live Streaming with FFGear and WriteGear Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/ffgear_ex.md This example shows how to set up a video stream using FFGear, configure FFmpeg parameters for YouTube Live, and stream using WriteGear. Ensure you replace the placeholder stream key with your actual YouTube Live stream key. ```python # import required libraries from vidgear.gears import FFGear from vidgear.gears import WriteGear import cv2 # open any valid video source with FFGear stream = FFGear(source="myvideo.mp4", frame_format="bgr24", logging=True).start() # define required FFmpeg parameters for YouTube Live output_params = { "-clones": ["-f", "lavfi", "-i", "anullsrc"], # add silent audio (required by YT) "-vcodec": "libx264", "-preset": "medium", "-b:v": "4500k", "-bufsize": "512k", "-pix_fmt": "yuv420p", "-f": "flv", } # [WARNING] Change your YouTube-Live Stream Key here: YOUTUBE_STREAM_KEY = "xxxx-xxxx-xxxx-xxxx-xxxx" # Define WriteGear writer with YouTube RTMP address writer = WriteGear( output="rtmp://a.rtmp.youtube.com/live2/{}".format(YOUTUBE_STREAM_KEY), logging=True, **output_params ) # loop over while True: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # write frame to writer writer.write(frame) # safely close video stream stream.stop() # safely close writer writer.close() ``` -------------------------------- ### NetGear_Async Server Setup for Video Streaming Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/usage.md Initializes and launches the NetGear_Async server using a webcam as the source. Ensure the 'address' is set to the client's IP. The stream can be terminated by pressing Ctrl+C. ```python # import libraries from vidgear.gears.asyncio import NetGear_Async import asyncio # initialize Server with suitable source server = NetGear_Async( source=0, address="192.168.x.xxx", port="5454", protocol="tcp", pattern=2, logging=True, ).launch() if __name__ == "__main__": # set event loop asyncio.set_event_loop(server.loop) try: # run your main function task until it is complete server.loop.run_until_complete(server.task) except (KeyboardInterrupt, SystemExit): # wait for interrupts pass finally: # finally close the server server.close() ``` -------------------------------- ### Netgear Server with Bidirectional Mode (Picamera2) Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear/advanced/bidirectional_mode.md Server-side code using the PiGear backend with Picamera2 to stream frames and exchange data bidirectionally with a Netgear client. Requires Raspberry Pi camera setup and Picamera2 installation. ```python # import required libraries from vidgear.gears import VideoGear from vidgear.gears import NetGear from vidgear.gears import PiGear from libcamera import Transform # add various Picamera2 API tweaks options = { "queue": True, "buffer_count": 4, "controls": {"Brightness": 0.5, "ExposureValue": 2.0}, "transform": Transform(hflip=1), "auto_align_output_config": True, # auto-align camera configuration } # open pi video stream with defined parameters stream = PiGear(resolution=(640, 480), framerate=60, logging=True, **options).start() # activate Bidirectional mode options = {"bidirectional_mode": True} # Define NetGear server at given IP address and define parameters # !!! change following IP address '192.168.x.xxx' with client's IP address !!! server = NetGear( address="192.168.x.xxx", port="5454", protocol="tcp", pattern=1, logging=True, **options ) # loop over until KeyBoard Interrupted while True: try: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # prepare data to be sent(a simple text in our case) target_data = "Hello, I am a Server." # send frame & data and also receive data from Client recv_data = server.send(frame, message=target_data) # (1) # print data just received from Client if not (recv_data is None): print(recv_data) except KeyboardInterrupt: break # safely close video stream stream.stop() # safely close server server.close() ``` -------------------------------- ### Select VideoGear Backend Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/videogear/params.md Demonstrates how to initialize VideoGear with different backend APIs using the `Backend` enum. Ensure the correct backend is chosen based on your hardware and requirements. ```python from vidgear.gears import VideoGear from vidgear.gears.helper import Backend VideoGear(api=Backend.CAMGEAR) # default — CamGear backend VideoGear(api=Backend.PIGEAR) # PiGear backend VideoGear(api=Backend.FFGEAR) # FFGear backend ``` -------------------------------- ### Dockerfile for Minimal VidGear Setup Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md This Dockerfile installs necessary dependencies for basic video file I/O using pip's opencv-python. It lacks GStreamer support, limiting access to network streams and advanced features. ```docker FROM python:3.10-slim RUN apt-get update && apt-get install -y \ ffmpeg \ libsm6 libxext6 libxrender-dev libgomp1 \ && rm -rf /var/lib/apt/lists/* WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt # ... rest of your app ``` -------------------------------- ### Initialize FFGear with dshow Demuxer and Device Index (Windows) Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/ffgear/advanced/index.md Example for initializing FFGear on Windows using the dshow demuxer, specifying a video device by its index. This is useful when multiple devices share similar names. ```python # define video_device_number as 1 (numbering start from 0) options = {"-ffprefixes":["-video_device_number", "1"]} stream = FFGear(source="Camera", source_demuxer="dshow", options=options, frame_format="bgr24", logging=True) ``` -------------------------------- ### WebGear with FFGear Backend Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/webgear_ex.md Initialize WebGear with the FFGear backend for hardware-accelerated video decoding. This example requires importing necessary libraries and configuring performance options. ```python # import libs import uvicorn from vidgear.gears.asyncio import WebGear from vidgear.gears.helper import Backend # various WebGear performance tweaks options = { "frame_size_reduction": 40, "jpeg_compression_quality": 80, "jpeg_compression_fastdct": True, "jpeg_compression_fastupsample": False, } # initialize WebGear app with FFGear backend web = WebGear( api=Backend.FFGEAR, source="foo.mp4", logging=True, **options, ) # run this app on Uvicorn server at address http://localhost:8000/ uvicorn.run(web(), host="localhost", port=8000) # close app safely web.shutdown() ``` -------------------------------- ### Advanced ScreenGear with Custom Class and WebGear_RTC Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/screengear_ex.md This example demonstrates an advanced integration using a custom streaming class with ScreenGear and WebGear_RTC. It requires implementing `start()`, `read()`, and `stop()` methods in the custom class. The `reducer` function is used to optimize frame size. ```python # import necessary libs import uvicorn, cv2 from vidgear.gears import ScreenGear from vidgear.gears.helper import reducer from vidgear.gears.asyncio import WebGear_RTC # create your own custom streaming class class Custom_Stream_Class: """ Custom Streaming using ScreenGear """ def __init__(self, backend="mss", logging=False): # !!! define your own video source here !!! self.source = ScreenGear(backend=backend, logging=logging) # define running flag self.running = True def start(self): # don't forget this function!!! # This function is specific to VideoCapture APIs only if not self.source is None: self.source.start() def read(self): # don't forget this function!!! # check if source was initialized or not if self.source is None: return None # check if we're still running if self.running: # read frame from provided source frame = self.source.read() # check if frame is available if not(frame is None): # do something with your OpenCV frame here # reducer frames size if you want more performance otherwise comment this line frame = reducer(frame, percentage=20) # reduce frame by 20% # return our gray frame return frame else: # signal we're not running now self.running = False # return None-type return None def stop(self): # don't forget this function!!! # flag that we're not running self.running = False # close stream if not self.source is None: self.source.stop() # assign your Custom Streaming Class with adequate ScreenGear parameters # to `custom_stream` attribute in options parameter options = {"custom_stream": Custom_Stream_Class(backend="pil", logging=True)} # initialize WebGear_RTC app without any source web = WebGear_RTC(logging=True, **options) # run this app on Uvicorn server at address http://localhost:8000/ uvicorn.run(web(), host="localhost", port=8000) # close app safely web.shutdown() ``` -------------------------------- ### Configure WebGear with FFGear Backend and Source Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/webgear/params.md Initialize WebGear with the FFGear backend, specifying the video source. The source can be a local file path or a network stream URL. ```python from vidgear.gears.helper import Backend WebGear(api=Backend.FFGEAR, source="myvideo.mp4") WebGear(api=Backend.FFGEAR, source="rtsp://192.168.1.10:554/stream") ``` -------------------------------- ### NetGear_Async Initialization Parameters Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/params.md Demonstrates how to initialize NetGear_Async with various parameters. ```APIDOC ## `receive_mode` This parameter select the Netgear's Mode of operation. It basically activates `Receive Mode`(_if `True`_) and `Send Mode`(_if `False`_). Furthermore, `recv()` method will only work when this flag is enabled(_i.e. `Receive Mode`_), whereas `send()` method will only work when this flag is disabled(_i.e.`Send Mode`_). **Data-Type:** Boolean **Default Value:** Its default value is `False`(_i.e. Send Mode is activated by default_). ### Usage: ```python NetGear_Async(receive_mode=True) # activates Recieve Mode ``` ## `timeout` In NetGear_Async, the Receiver-end keeps tracks if frames are received from Server-end within this specified timeout value _(in seconds)_, Otherwise `TimeoutError` will be raised, which helps to close the Receiver-end safely if the Server has lost connection prematurely. This parameter controls that timeout value _(i.e. the maximum waiting time (in seconds))_ after which Client exit itself with a `TimeoutError` to save resources. Its minimum value is `0.0` but no max limit. **Data-Type:** Float/Integer **Default Value:** Its default value is `10.0`. ### Usage: ```python NetGear_Async(timeout=5.0) # sets 5secs timeout ``` ## `options` This parameter provides the flexibility to alter various NetGear_Async API's internal properties and modes. **Data-Type:** Dictionary **Default Value:** Its default value is `{}` ### Usage: !!! abstract "Supported dictionary attributes for NetGear_Async API" * **`bidirectional_mode`** (_boolean_) : This internal attribute activates the exclusive [**Bidirectional Mode**](../advanced/bidirectional_mode/), if enabled(`True`). The desired attributes can be passed to NetGear_Async API as follows: ```python # formatting parameters as dictionary attributes options = { "bidirectional_mode": True, } # assigning it NetGear_Async(logging=True, **options) ``` ``` -------------------------------- ### ScreenGear Direct Colorspace Manipulation Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/screengear/usage.md This example demonstrates how to dynamically change the colorspace of the screen capture stream using ScreenGear. It starts with HSV, then switches to GRAY, LAB, and back to the default BGR based on key presses. Incorrect colorspace values will revert to BGR. ```python # import required libraries from vidgear.gears import ScreenGear import cv2 # Change colorspace to `HSV` stream = ScreenGear(colorspace="COLOR_BGR2HSV", logging=True).start() # loop over while True: # read HSV frames frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the HSV frame here} # Show output window cv2.imshow("Output Frame", frame) # check for key if pressed key = cv2.waitKey(1) & 0xFF # check if 'w' key is pressed if key == ord("w"): # directly change colorspace at any instant stream.color_space = cv2.COLOR_BGR2GRAY # Now colorspace is GRAY # check for 'e' key is pressed if key == ord("e"): stream.color_space = cv2.COLOR_BGR2LAB # Now colorspace is CieLAB # check for 's' key is pressed if key == ord("s"): stream.color_space = None # Now colorspace is default(ie BGR) # check for 'q' key is pressed if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### Install GUI Dependencies for Pip Installation Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/poetry_install.md These commands install the necessary GUI dependencies for installing Picamera2 via pip. ```sh sudo apt install -y python3-pyqt5 python3-opengl ``` -------------------------------- ### Environment File Template (.env.example) Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md A sample .env.example file illustrating common configuration options for a VidGear streaming application. It covers input source, output parameters, and processing options. ```bash # ========================================== # Input Source Configuration # ========================================== VIDEO_URL=https://youtu.be/xvFZjo5PgG0 VIDEO_STREAM_QUALITY=best # Options: best, 1080p, 720p, 480p AUDIO_STREAM_QUALITY=bestaudio # Options: bestaudio, 192, 128 # ========================================== # Output Configuration # ========================================== OUTPUT_FILE=/app/output/vidgear_output.mp4 OUTPUT_CODEC=libx264 # Options: libx264, libx265, libvpx AUDIO_CODEC=aac # Options: aac, mp3, libopus # ========================================== # Processing Options # ========================================== FRAME_LIMIT=0 # 0 = process entire video VERBOSE=false # Enable debug logging ``` -------------------------------- ### Initialize and Run WebGear Server Source: https://github.com/abhitronix/vidgear/blob/master/README.md Initializes a WebGear video broadcasting server with specified performance options and runs it using Uvicorn. Ensure to close the app safely after use. ```python import uvicorn from vidgear.gears.asyncio import WebGear # various performance tweaks options = { "frame_size_reduction": 40, "jpeg_compression_quality": 80, "jpeg_compression_fastdct": True, "jpeg_compression_fastupsample": False, } # initialize WebGear app web = WebGear(source="foo.mp4", logging=True, **options) # run this app on Uvicorn server at address http://localhost:8000/ uvicorn.run(web(), host="localhost", port=8000) # close app safely web.shutdown() ``` -------------------------------- ### Client Setup for Multi-Server Bidirectional Mode Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear/advanced/multi_server.md This Python code configures a NetGear client to connect to multiple servers simultaneously, enabling both video frame reception and bidirectional data transfer. It displays a montage of received frames and prints any received data to the console. Ensure 'imutils' is installed for frame montage functionality. ```python # import required libraries from vidgear.gears import NetGear from imutils import build_montages # (1) import cv2 # activate both multiserver and bidirectional modes options = {"multiserver_mode": True, "bidirectional_mode": True} # Define NetGear Client at given IP address and assign list/tuple of all unique Server((5577,5578) in our case) and other parameters # !!! change following IP address '192.168.x.xxx' with yours !!! client = NetGear( address="192.168.x.x", port=(5577, 5578), protocol="tcp", pattern=1, receive_mode=True, logging=True, **options ) # Define received frame dictionary frame_dict = {} # loop over until Keyboard Interrupted while True: try: # prepare data to be sent target_data = "Hi, I am a Client here." # receive data from server(s) and also send our data data = client.recv(return_data=target_data) # check if data received isn't None if data is None: break # extract unique port address and its respective frame and received data unique_address, extracted_data, frame = recv_data # {do something with the extracted frame and data here} # let's display extracted data on our extracted frame cv2.putText( frame, extracted_data, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2, ) # get extracted frame's shape (h, w) = frame.shape[:2] # update the extracted frame in the frame dictionary frame_dict[unique_address] = frame # build a montage using data dictionary montages = build_montages(frame_dict.values(), (w, h), (2, 1)) # display the montage(s) on the screen for (i, montage) in enumerate(montages): cv2.imshow("Montage Footage {}".format(i), montage) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break except KeyboardInterrupt: break # close output window cv2.destroyAllWindows() # safely close client client.close() ``` -------------------------------- ### Configure NetGear Async with FFGear Backend and Source Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/params.md Initialize NetGear_Async with the FFGear backend and specify the video source. The source can be a local file or a network stream URL. ```python from vidgear.gears.helper import Backend NetGear_Async(api=Backend.FFGEAR, source="myvideo.mp4") ``` ```python from vidgear.gears.helper import Backend NetGear_Async(api=Backend.FFGEAR, source="rtsp://192.168.1.10:554/stream") ``` -------------------------------- ### NVIDIA CUDA Decoding with FFGear Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/ffgear/advanced/index.md Utilize NVIDIA CUDA for hardware-accelerated decoding, scaling, and frame rate adjustments directly on the GPU. This example configures FFGear to keep frames in GPU memory until explicitly downloaded, optimizing performance for CUDA-enabled hardware. Ensure your environment supports CUDA and has the necessary drivers installed. ```python # import required libraries from vidgear.gears import FFGear import cv2 # CUDA hwaccel: decode in GPU memory, scale & fps in GPU, download as NV12 options = { "-vcodec": None, # skip source decoder, let FFmpeg choose "-enforce_cv_patch": True, # auto-convert NV12 → OpenCV Compatible in FFGear "-ffprefixes": [ "-vsync", "0", # prevent duplicate frames "-hwaccel", "cuda", # use CUDA accelerator "-hwaccel_output_format", "cuda", # keep frames in GPU memory ], "-custom_resolution": "null", # discard source resolution param "-framerate": "null", # discard source framerate param "-vf": ( "scale_cuda=1280:720," # GPU-side scale to 1280x720 "fps=60.0," # GPU-side framerate "hwdownload," # download to system memory "format=nv12" # convert to NV12 pixel format ), } stream = FFGear( source=VIDEO, frame_format="null", # discard source pixel format logging=True, **options ).start() # loop over while True: # read NV12 frames frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # convert it to OpenCV compatible frame frame = cv2.cvtColor(frame, cv2.COLOR_YUV2BGR_NV12) # {do something with the BGR frame here} # Show output window cv2.imshow("Output", frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### Capture Entire Desktop on Linux with x11grab Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/ffgear/advanced/index.md This example demonstrates capturing the entire desktop on Linux using the 'x11grab' demuxer. It includes setting a framerate and displaying the captured frames. ```python # import required libraries from vidgear.gears import FFGear import cv2 # define framerate options = {"-framerate": "30"} # stream with ":0.0" desktop source(starting with the upper-left corner at x=10, y=20) # for BGR24 output stream = FFGear( source=":0.0", source_demuxer="x11grab", frame_format="bgr24", logging=True, **options ).start() # loop over while True: # read BGR frames (auto-converted from YUV420p) frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # Show output window cv2.imshow("Output", frame) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() ``` -------------------------------- ### Screen Recording and Processing with WriteGear Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/screengear/usage.md This example shows how to capture a specific region of your screen using ScreenGear and then process each frame (e.g., convert to grayscale) before saving it using WriteGear. Ensure you have the necessary libraries (vidgear, opencv-python) installed. The code captures a defined screen area, processes frames, and saves them to 'Output.mp4'. Press 'q' to exit. ```python # import required libraries from vidgear.gears import ScreenGear from vidgear.gears import WriteGear import cv2 # define dimensions of screen w.r.t to given monitor to be captured options = {"top": 40, "left": 0, "width": 100, "height": 100} # define suitable (Codec,CRF,preset) FFmpeg parameters for writer output_params = {"-vcodec": "libx264", "-crf": 0, "-preset": "fast"} # open video stream with defined parameters stream = ScreenGear(monitor=1, logging=True, **options).start() # Define writer with defined parameters and suitable output filename for e.g. `Output.mp4` writer = WriteGear(output="Output.mp4", logging=True, **output_params) # loop over while True: # read frames from stream frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # lets convert frame to gray for this example gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # write gray frame to writer writer.write(gray) # Show output window cv2.imshow("Output Gray Frame", gray) # check for 'q' key if pressed key = cv2.waitKey(1) & 0xFF if key == ord("q"): break # close output window cv2.destroyAllWindows() # safely close video stream stream.stop() # safely close writer writer.close() ``` -------------------------------- ### Install aiortc Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/webgear_rtc/usage.md Install the aiortc library, which is required for the WebGear_RTC API. Ensure you have Microsoft C++ build tools installed on Windows if necessary. ```sh pip install aiortc ``` -------------------------------- ### Server-Side Stream Setup with NetGear_Async Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/usage.md Initializes and launches NetGear_Async on the server to stream video frames with stabilization enabled. Ensure the event loop is correctly set and the task is run until completion or interruption. ```python # import libraries from vidgear.gears.asyncio import NetGear_Async import asyncio # initialize Server with suitable source and enable stabilization server = NetGear_Async( source="/home/foo/foo1.mp4", stabilize=True, logging=True ).launch() if __name__ == "__main__": # set event loop asyncio.set_event_loop(server.loop) try: # run your main function task until it is complete server.loop.run_until_complete(server.task) except (KeyboardInterrupt, SystemExit): # wait for interrupts pass finally: # finally close the server server.close() ``` -------------------------------- ### Install OpenCV Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Install the opencv-python package, which is a critical prerequisite for VidGear's core functionalities. Ensure you do not install both pip and source versions together. ```sh pip install opencv-python ``` -------------------------------- ### Install Paramiko for SSH Tunneling Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear/advanced/ssh_tunnel.md Install the Paramiko library, a dependency for SSH tunneling mode. This is compatible with all platforms and automatically enabled in ZeroMQ if installed. ```sh # install paramiko pip install paramiko ``` -------------------------------- ### Initialize NetGear Async with Specific Backend Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear_async/params.md Manually select a backend for OpenCV's VideoCapture, such as `cv2.CAP_DSHOW`, by passing the backend flag. ```python NetGear_Async(source=0, backend = cv2.CAP_DSHOW) ``` -------------------------------- ### Initialize FFGear with Camera Source (dshow) Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/ffgear/advanced/index.md Initializes FFGear to capture video from a camera device using the 'dshow' demuxer for BGR24 output. Requires specifying 'Camera' as the source. ```python stream = FFGear(source="Camera", source_demuxer="dshow", frame_format="bgr24", logging=True, **options) ``` -------------------------------- ### Install OpenSSH Server on Linux Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/netgear/advanced/ssh_tunnel.md Installs the OpenSSH server package on Debian-based or RHEL-based Linux distributions. Ensure this is installed on the client machine for SSH tunneling. ```sh # Debian-based sudo apt-get install openssh-server # RHEL-based sudo yum install openssh-server ``` -------------------------------- ### Install VidGear with Bare-Minimum Dependencies Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Install the core VidGear package without extra dependencies. You may need to manually install critical and API-specific dependencies afterward. ```sh pip install -U vidgear ``` ```sh pip install opencv-python ``` ```sh pip install ``` -------------------------------- ### Initialize FFGear with v4l2 Demuxer (Linux) Source: https://github.com/abhitronix/vidgear/blob/master/docs/gears/ffgear/advanced/index.md Example of initializing FFGear to capture video from a USB webcam on Linux using the `video4linux2` (v4l2) demuxer. It specifies the device path and requests BGR24 frame format. ```python # initialize and formulate the stream with /dev/video0 source for BGR24 output stream = FFGear(source="/dev/video0", source_demuxer="v4l2", frame_format="bgr24", logging=True) ``` -------------------------------- ### Install VidGear and Dependencies Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md Installs VidGear and its required Python packages using pip. It's recommended to install system dependencies first, then Python build dependencies, and finally VidGear. ```docker # 1. System dependencies first RUN apt-get update && apt-get install -y ffmpeg gstreamer1.0-tools ... # 2. Python build dependencies (if building packages) RUN pip install --upgrade pip setuptools wheel # 3. VidGear and its dependencies RUN pip install vidgear[asyncio] # 4. Optional: yt-dlp for streaming from YouTube/Twitch RUN pip install --upgrade "yt-dlp[default]" ``` -------------------------------- ### Update System and Install Picamera2 with GUI Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/pip_install.md Recommended for Raspberry Pi OS, this updates your system and installs Picamera2 with all GUI dependencies. Ensure you uninstall any previous pip installations of Picamera2 first. ```sh sudo apt update && upgrade sudo apt install -y python3-picamera2 ``` -------------------------------- ### Optimize Docker Image Size with Multi-Stage Builds Source: https://github.com/abhitronix/vidgear/blob/master/docs/bonus/docker_example.md This example illustrates a solution for large Docker image sizes by recommending the use of multi-stage builds. It advises against including build tools and development packages in the final runtime image, suggesting only necessary binaries be copied. ```dockerfile # Don't include in runtime: # build-essential, cmake, git, *-dev packages (except runtime libs) ``` -------------------------------- ### Verify Poetry Installation Source: https://github.com/abhitronix/vidgear/blob/master/docs/installation/poetry_install.md Use this command to check if Poetry is installed correctly on your system. ```sh poetry --version ``` -------------------------------- ### Server (FFGear + NetGear) Example Source: https://github.com/abhitronix/vidgear/blob/master/docs/help/ffgear_ex.md This server-side code uses FFGear to read video frames from a source and NetGear to stream them to a client. Ensure the IP address and port are correctly configured. JPEG compression is enabled for performance. ```python # import required libraries from vidgear.gears import FFGear from vidgear.gears import NetGear import cv2 # activate JPEG compression for performance options = { "jpeg_compression": True, "jpeg_compression_quality": 90, "jpeg_compression_fastdct": True, "jpeg_compression_fastupsample": True, } # open video source with FFGear stream = FFGear(source="myvideo.mp4", frame_format="bgr24", logging=True).start() # Define NetGear Server # !!! change '192.168.x.xxx' with your Client's IP address !!! server = NetGear( address="192.168.x.xxx", port="5454", protocol="tcp", pattern=1, logging=True, **options ) # loop over until KeyBoard Interrupted while True: try: # read frames from FFGear frame = stream.read() # check for frame if Nonetype if frame is None: break # {do something with the frame here} # send frame to client server.send(frame) except KeyboardInterrupt: break # safely close FFGear stream stream.stop() # safely close NetGear server server.close() ```