WebGear by default only supports "BGR" colorspace frames as input, but you can use jpeg_compression_colorspace string attribute through its options dictionary parameter to specify incoming frames colorspace.
Let's implement a bare-minimum example using WebGear, where we will be sending GRAY frames to client browser:
In H.264 Mode, jpeg_compression_colorspace only tells FFmpeg the input frames' pixel format, while JPEG attributes apply to the MJPEG fallback stream only.
Supported jpeg_compression_colorspace colorspace values are RGB, BGR, RGBX, BGRX, XBGR, XRGB, GRAY, RGBA, BGRA, ABGR, ARGB, CMYK. More information can be found here âž¶
# import required librariesimportuvicornfromvidgear.gears.asyncioimportWebGear# MJPEG mode with various performance tweaks, and enable grayscale inputoptions={"frame_size_reduction":25,"jpeg_compression_colorspace":"GRAY",# set grayscale"jpeg_compression_quality":90,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":True,}# initialize WebGear app and change its colorspace to grayscaleweb=WebGear(source="foo.mp4",colorspace="COLOR_BGR2GRAY",streaming_mode="mjpeg",logging=True,**options)# run this app on Uvicorn server at address http://0.0.0.0:8000/uvicorn.run(web(),host="0.0.0.0",port=8000)# close app safelyweb.shutdown()
# import required librariesimportuvicornfromvidgear.gears.asyncioimportWebGear# H.264 mode and enable grayscale inputoptions={"frame_size_reduction":25,"jpeg_compression_colorspace":"GRAY",# set grayscale}# initialize WebGear app and change its colorspace to grayscaleweb=WebGear(source="foo.mp4",colorspace="COLOR_BGR2GRAY",streaming_mode="h264",logging=True,**options)# run this app on Uvicorn server at address http://0.0.0.0:8000/uvicorn.run(web(),host="0.0.0.0",port=8000)# close app safelyweb.shutdown()
And that's all, Now you can see output at http://localhost:8000/ address on your local machine.
Custom Sources only work in MJPEG Mode, since they yield ready-made JPEG bytes. Setting streaming_mode="h264" with a Custom Source falls back to MJPEG anyway.
Let's implement a bare-minimum example with a Custom Source using WebGear API and OpenCV:
# import necessary libsimportuvicorn,asyncio,cv2fromvidgear.gears.asyncioimportWebGearfromvidgear.gears.asyncio.helperimportreducer# initialize WebGear app without any source in MJPEG modeweb=WebGear(logging=True,streaming_mode="mjpeg")# create your own custom frame producerasyncdefmy_frame_producer():# !!! define your own video source here !!!# Open any video stream such as live webcam # video stream on first index(i.e. 0) devicestream=cv2.VideoCapture(0)# 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,interpolation=cv2.INTER_AREA)# reduce frame by 30%# handle JPEG encodingencodedImage=cv2.imencode(".jpg",frame)[1].tobytes()# yield frame in byte formatyield(b"--frame\r\nContent-Type:image/jpeg\r\n\r\n"+encodedImage+b"\r\n")awaitasyncio.sleep(0)# close streamstream.release()# add your custom frame producer to configweb.config["generator"]=my_frame_producer# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
# import libsimportuvicornfromstarlette.routingimportMountfromstarlette.staticfilesimportStaticFilesfromvidgear.gears.asyncioimportWebGear# MJPEG mode with various performance tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,}# initialize WebGear appweb=WebGear(source="foo.mp4",streaming_mode="mjpeg",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# append new route i.e. mount another folder called `test` located at `/home/foo/.vidgear/test` directoryweb.routes.append(Mount("/test",app=StaticFiles(directory="/home/foo/.vidgear/test"),name="test"))# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
# import libsimportuvicornfromstarlette.routingimportMountfromstarlette.staticfilesimportStaticFilesfromvidgear.gears.asyncioimportWebGear# H.264 mode with encoder tweaksoptions={"frame_size_reduction":40,"h264_options":{"-crf":23},}# initialize WebGear appweb=WebGear(source="foo.mp4",streaming_mode="h264",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# append new route i.e. mount another folder called `test` located at `/home/foo/.vidgear/test` directoryweb.routes.append(Mount("/test",app=StaticFiles(directory="/home/foo/.vidgear/test"),name="test"))# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
Then you can use this folder in your HTML page, to host data-files. For example, if we have jQuery script jquery-3.3.1.slim.min.js in this folder and want to integrate it, then, we can do something like this:
# import libsimportuvicorn,asynciofromstarlette.templatingimportJinja2Templatesfromstarlette.routingimportRoutefromvidgear.gears.asyncioimportWebGear# Build out Jinja2 template render at `/home/foo/.vidgear/custom_template` path in which our `hello.html` file is locatedtemplate=Jinja2Templates(directory="/home/foo/.vidgear/custom_template")# render and return our webpage templateasyncdefhello_world(request):returntemplate.TemplateResponse(request,"hello.html")# MJPEG mode with various performance tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,}# initialize WebGear app with a valid sourceweb=WebGear(source="/home/foo/foo1.mp4",streaming_mode="mjpeg",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# append new route to point our rendered webpageweb.routes.append(Route("/hello",endpoint=hello_world))# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
# import libsimportuvicorn,asynciofromstarlette.templatingimportJinja2Templatesfromstarlette.routingimportRoutefromvidgear.gears.asyncioimportWebGear# Build out Jinja2 template render at `/home/foo/.vidgear/custom_template` path in which our `hello.html` file is locatedtemplate=Jinja2Templates(directory="/home/foo/.vidgear/custom_template")# render and return our webpage templateasyncdefhello_world(request):returntemplate.TemplateResponse(request,"hello.html")# H.264 mode with encoder tweaksoptions={"frame_size_reduction":40,"h264_options":{"-crf":23},}# initialize WebGear app with a valid sourceweb=WebGear(source="/home/foo/foo1.mp4",streaming_mode="h264",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# append new route to point our rendered webpageweb.routes.append(Route("/hello",endpoint=hello_world))# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
For this example, let's use CORSMiddleware for implementing appropriate CORS headers to outgoing responses in our application in order to allow cross-origin requests from browsers, as follows:
The default parameters used by the CORSMiddleware implementation are restrictive by default, so you'll need to explicitly enable particular origins, methods, or headers, in order for browsers to be permitted to use them in a Cross-Domain context.
Starlette provides several arguments for enabling origins, methods, or headers for CORSMiddleware API. More information can be found here âž¶
# import libsimportuvicorn,asynciofromstarlette.middlewareimportMiddlewarefromstarlette.middleware.corsimportCORSMiddlewarefromvidgear.gears.asyncioimportWebGear# MJPEG mode with various performance tweaksoptions={"frame_size_reduction":40,"jpeg_compression_quality":80,"jpeg_compression_fastdct":True,"jpeg_compression_fastupsample":False,}# initialize WebGear app with a valid sourceweb=WebGear(source="/home/foo/foo1.mp4",streaming_mode="mjpeg",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# define and assign suitable cors middlewaresweb.middleware=[Middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)]# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
# import libsimportuvicorn,asynciofromstarlette.middlewareimportMiddlewarefromstarlette.middleware.corsimportCORSMiddlewarefromvidgear.gears.asyncioimportWebGear# H.264 mode with encoder tweaksoptions={"frame_size_reduction":40,"h264_options":{"-crf":23},}# initialize WebGear app with a valid sourceweb=WebGear(source="/home/foo/foo1.mp4",streaming_mode="h264",logging=True,**options)# enable source i.e. `test.mp4` and enable `logging` for debugging# define and assign suitable cors middlewaresweb.middleware=[Middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)]# run this app on Uvicorn server at address http://localhost:8000/uvicorn.run(web(),host="localhost",port=8000)# close app safelyweb.shutdown()
You allowed to alter/change code in all existing default downloaded files at your convenience without any restrictions.
You allowed to delete/rename all existing data files, except remember NOT to delete/rename three critical data-files (i.e index.html, 404.html & 500.html) present in templates folder, and two script files (i.e custom.js & videoFrameDecoderWorker.js) present in static/js folder inside the webgear directory at the default location, otherwise, it will trigger Auto-generation process, and it will overwrite the existing files with Server ones.
You're allowed to add/mount any number of additional folder as shown in this example above.
You're allowed to delete/rename existing folders at the default location except remember NOT to delete/rename templates folder in the webgear directory where critical data-files (i.e index.html, 404.html & 500.html) are located, otherwise, it will trigger Auto-generation process.