Skip to content

Instantly share code, notes, and snippets.

@Saren-Arterius
Created March 13, 2015 08:19
Show Gist options
  • Save Saren-Arterius/3326cdf1025da3c6f9ab to your computer and use it in GitHub Desktop.
Save Saren-Arterius/3326cdf1025da3c6f9ab to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from io import BytesIO
from subprocess import check_output
import sys
from PIL import Image, ImageDraw
MAX_VALUE = 255
MIN_VALUE = 0
DESIRED_BRIGHTNESS = 128
BRIGHTNESS_ALLOWANCE = 6
STEP = 1
MIN_GAIN = 6
TEXT_SHADOW_OFFSET = 1
TEXT_SHADOW_X = 4
TEXT_SHADOW_Y_OFFSET = 13
class WebcamBrightness(object):
def __init__(self, image):
box = int(image.size[0] / 3), int(image.size[1] / 3), int(image.size[0] * (2 / 3)), int(image.size[1] * (2 / 3))
self.image = image.convert("L").crop(box)
def get_brightness(self):
s = 0
for x in range(self.image.size[0]):
for y in range(self.image.size[1]):
s += self.image.getpixel((x, y))
return s / (self.image.size[0] * self.image.size[1])
@staticmethod
def get_webcam_bytes():
return check_output(["fswebcam", "-q", "--jpeg", "100", "--banner-colour",
"#FF000000", "--line-colour", "#FF000000", "/dev/stdout"])
@staticmethod
def get_webcam_screenshot():
b = BytesIO(WebcamBrightness.get_webcam_bytes())
return Image.open(b)
@staticmethod
def get_webcam_config():
return int(check_output(["v4l2-ctl", "-C", "exposure"]).decode().split(": ")[1]), \
int(check_output(["v4l2-ctl", "-C", "gain"]).decode().split(": ")[1])
@staticmethod
def set_webcam_config(exposure, gain):
check_output(["v4l2-ctl", "-c", "exposure={0},gain={1}".format(exposure, gain)])
@staticmethod
def tune_webcam(image):
wb = WebcamBrightness(image)
brightness = wb.get_brightness()
exposure, gain = WebcamBrightness.get_webcam_config()
if brightness < DESIRED_BRIGHTNESS - BRIGHTNESS_ALLOWANCE:
if exposure == MAX_VALUE:
WebcamBrightness.set_webcam_config(exposure, gain + STEP)
else:
WebcamBrightness.set_webcam_config(exposure + STEP, gain)
elif brightness > DESIRED_BRIGHTNESS + BRIGHTNESS_ALLOWANCE:
if gain - STEP >= MIN_GAIN:
WebcamBrightness.set_webcam_config(exposure, gain - STEP)
elif exposure != MIN_VALUE:
WebcamBrightness.set_webcam_config(exposure - STEP, gain)
return brightness, exposure, gain
if __name__ == "__main__":
image = WebcamBrightness.get_webcam_screenshot()
info = WebcamBrightness.tune_webcam(image)
draw = ImageDraw.Draw(image)
draw.text((TEXT_SHADOW_X + TEXT_SHADOW_OFFSET, image.size[1] - TEXT_SHADOW_Y_OFFSET + TEXT_SHADOW_OFFSET),
"B: {0:.2f}, E: {1}, G: {2}".format(info[0], info[1], info[2]), fill=(0, 0, 0))
draw.text((TEXT_SHADOW_X, image.size[1] - TEXT_SHADOW_Y_OFFSET),
"B: {0:.2f}, E: {1}, G: {2}".format(info[0], info[1], info[2]), fill=(255, 255, 255))
buffer = BytesIO()
image.save(buffer, "JPEG", quality=97)
buffer.seek(0)
sys.stdout.buffer.write(buffer.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment