Hacking a webcam with python
During lockdown, like everyone I have spent a lot of time on video calls. As such, I have problems with my cheap webcam, which came without any software (mostly whitebalancing issues). I thought I would try and modify the input with code!
Introduction
I am doing this on Ubuntu and have not tried to do this on any other OS.
The process will be: webcam input -- code -- output to virtual camera
To do this I am using v4l video for linux which can be installed with:
sudo apt-get install v4l2loopback-utils
Now we need to create a virtual device for our system to use.
sudo modprobe v4l2loopback devices=1
Now we have a virtual device - on my system it is at /dev/video2 We also need to install pyfakewebcam, to send the data to our virtual webcam. Now we can write some code to modify our webcam.
import pyfakewebcam
import cv2
cam = cv2.VideoCapture(0)
camera = pyfakewebcam.FakeWebcam('/dev/video2', 640, 480)
def get_frame(cam):
ret_val, img = cam.read()
img = cv2.resize(img, (640,480), interpolation = cv2.INTER_AREA)
return img
while True:
frame = get_frame(cam)
camera.schedule_frame(frame)
The only issue I had was the webcam input size and the output, you need to make sure these match!
Other than that all you have to do is modify the image (frame) however you wish. In future I intend to add a filter
that will remove the background or blur it like you can do on MS: teams (and probably many others).
There may be many other ways of doing this, but this is the way I found to do it.