Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
change webcam settings in realtime
#!/usr/bin/env python3
# Do violence to the Logitech C920s webcam settings in realtime
# To annoy your Zoom-mates by constantly changing the image
from pynput.keyboard import Listener
import os, sys
import random
import time
# Find out the name of the webcam device
lines = os.popen('v4l2-ctl --list-devices').read().lower().split('\n')
for i, line in enumerate(lines):
if 'webcam' in line:
device = lines[i+1].strip()
print(f"device = [{device}]")
#device = '/dev/video3' # on my system.
# parse the set of available (integer) controls
prefix_cmd = 'v4l2-ctl -d ' + device + ' '
ctrls_str = os.popen(prefix_cmd + '--list-ctrls | grep -v inactive | grep "\(int\)"').read()
ctrls = []
for line in ctrls_str.split('\n'):
words = line.strip().split()
if ([] == words): break
name, minval, maxval, stepval, value = words[0], int(words[4][4:]), \
int(words[5][4:]), int(words[6][5:]), (words[8][6:])
ctrls.append([name, minval, maxval, stepval, value])
print("ctrls = ",ctrls)
# Now go nuts
keep_running, reset = True, False
def on_press(key): # how to make it stop
global keep_running, reset
if key.char in ['q','r']:
keep_running = False
if 'r' == key.char: reset=True
return False # shutdown the listener
listener = Listener(on_press=on_press)
while keep_running==True:
s = prefix_cmd
for c in ctrls:
val = random.randrange(c[1], c[2], c[3])
s += '--set-ctrl='+c[0]+'='+str(val)+' '
time.sleep(.5) # wait 500 ms, because driver can't keep up
# graceful exit
if reset: # reset is because sometimes the program hangs and you get stuck with weird webcam settings
print("\nOkay, stopping. Restoring factory webcam settings:")
s = f'v4l2-ctl -d {device} --set-ctrl=brightness=128 --set-ctrl=contrast=128 --set-ctrl=saturation=128 --set-ctrl=gain=255 --set-ctrl=sharpness=128 --set-ctrl=backlight_compensation=0 --set-ctrl=pan_absolute=0 --set-ctrl=tilt_absolute=0 --set-ctrl=zoom_absolute=120'
print("\nOkay, stopping. Restoring previous webcam settings:")
s = prefix_cmd
for c in ctrls:
s += '--set-ctrl='+c[0]+'='+str(c[4])+' '
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment