Skip to content

Instantly share code, notes, and snippets.

@drscotthawley
Created June 2, 2021 19:38
Show Gist options
  • Save drscotthawley/e2e39babfe52bb12b708a4d93a0e9781 to your computer and use it in GitHub Desktop.
Save drscotthawley/e2e39babfe52bb12b708a4d93a0e9781 to your computer and use it in GitHub Desktop.
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()
break
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)
listener.start()
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)+' '
print(s)
os.system(s)
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'
else:
print("\nOkay, stopping. Restoring previous webcam settings:")
s = prefix_cmd
for c in ctrls:
s += '--set-ctrl='+c[0]+'='+str(c[4])+' '
print(s)
os.system(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment