Because of WebGear API's flexible internal wapper around VideoGear, it can easily access any parameter of CamGear and PiGear videocapture APIs.
Following usage examples are just an idea of what can be done with WebGear API, you can try various VideoGear, CamGear and PiGear parameters directly in WebGear API in the similar manner.
Here's a bare-minimum example of using WebGear API with the Raspberry Pi camera module while tweaking its various properties in few lines of python code:
Backend PiGear API now fully supports the newer picamera2 python library under the hood for Raspberry Pi camera modules. Follow this guide ➶ for its installation.
# import libsimportuvicornfromlibcameraimportTransformfromvidgear.gears.asyncioimportWebGear# various WebGear_RTC performance # and Picamera2 API tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,"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}# initialize WebGear appweb=WebGear(enablePiCamera=True,resolution=(640,480),framerate=60,logging=True,**options)# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
Under the hood, Backend PiGear API (version 0.3.3 onwards) prioritizes the new picamera2 API backend.
However, the API seamlessly switches to the legacy picamera backend, if the picamera2 library is unavailable or not installed.
It is advised to enable logging(logging=True) to see which backend is being used.
The picamera library is built on the legacy camera stack that is NOT (and never has been) supported on 64-bit OS builds.
You could also enforce the legacy picamera API backend in PiGear by using the enforce_legacy_picamera user-defined optional parameter boolean attribute.
# import libsimportuvicornfromvidgear.gears.asyncioimportWebGear# various webgear performance and Picamera API tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,"hflip":True,"exposure_mode":"auto","iso":800,"exposure_compensation":15,"awb_mode":"horizon","sensor_mode":0,}# initialize WebGear appweb=WebGear(enablePiCamera=True,resolution=(640,480),framerate=60,logging=True,**options)# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
Using WebGear with real-time Video Stabilization enabled¶
Here's an example of using WebGear API with real-time Video Stabilization enabled:
# import libsimportuvicornfromvidgear.gears.asyncioimportWebGear# various webgear performance tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,}# initialize WebGear app with a raw source and enable video stabilization(`stabilize=True`)web=WebGear(source="foo.mp4",stabilize=True,logging=True,**options)# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
In this example, we'll be displaying two video feeds side-by-side simultaneously on browser using WebGear API by defining two separate frame generators:
New in v0.2.2
This example was added in v0.2.2.
Step-1 (Trigger Auto-Generation Process): Firstly, run this bare-minimum code to trigger the Auto-generation process, this will create .vidgear directory at current location (directory where you'll run this code):
# import required librariesimportuvicornfromvidgear.gears.asyncioimportWebGear# provide current directory to save data filesoptions={"custom_data_location":"./"}# initialize WebGear appweb=WebGear(source=0,logging=True,**options)# close app safelyweb.shutdown()
Step-2 (Replace HTML file): Now, go inside .vidgearwebgeartemplates directory at current location of your machine, and there replace content of index.html file with following:
# import necessary libsimportuvicorn,asyncio,cv2fromvidgear.gears.asyncioimportWebGearfromvidgear.gears.asyncio.helperimportreducerfromstarlette.responsesimportStreamingResponsefromstarlette.routingimportRoute# provide current directory to load data filesoptions={"custom_data_location":"./"}# initialize WebGear app without any sourceweb=WebGear(logging=True,**options)# create your own custom frame producerasyncdefmy_frame_producer1():# !!! define your first video source here !!!# Open any video stream such as "foo1.mp4"stream=cv2.VideoCapture("foo1.mp4")# loop over frameswhileTrue:# read frame from provided source(grabbed,frame)=stream.read()# break if NoneTypeifnotgrabbed:break# do something with your OpenCV frame here# reducer frames size if you want more performance otherwise comment this lineframe=awaitreducer(frame,percentage=30)# reduce frame by 30%# handle JPEG encodingencodedImage=cv2.imencode(".jpg",frame)[1].tobytes()# yield frame in byte formatyield(b"--frame\r\nContent-Type:video/jpeg2000\r\n\r\n"+encodedImage+b"\r\n")awaitasyncio.sleep(0.00001)# close streamstream.release()# create your own custom frame producerasyncdefmy_frame_producer2():# !!! define your second video source here !!!# Open any video stream such as "foo2.mp4"stream=cv2.VideoCapture("foo2.mp4")# loop over frameswhileTrue:# read frame from provided source(grabbed,frame)=stream.read()# break if NoneTypeifnotgrabbed:break# do something with your OpenCV frame here# reducer frames size if you want more performance otherwise comment this lineframe=awaitreducer(frame,percentage=30)# reduce frame by 30%# handle JPEG encodingencodedImage=cv2.imencode(".jpg",frame)[1].tobytes()# yield frame in byte formatyield(b"--frame\r\nContent-Type:video/jpeg2000\r\n\r\n"+encodedImage+b"\r\n")awaitasyncio.sleep(0.00001)# close streamstream.release()asyncdefcustom_video_response(scope):""" Return a async video streaming response for `my_frame_producer2` generator """assertscope["type"]in["http","https"]awaitasyncio.sleep(0.00001)returnStreamingResponse(my_frame_producer2(),media_type="multipart/x-mixed-replace; boundary=frame",)# add your custom frame producer to configweb.config["generator"]=my_frame_producer1# append new route i.e. new custom route with custom responseweb.routes.append(Route("/video2",endpoint=custom_video_response))# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
On successfully running this code, the output stream will be displayed at address http://localhost:8000/ in Browser.