Skip to content

Instantly share code, notes, and snippets.

@UltraWelfare
Last active December 14, 2018 20:02
Show Gist options
  • Save UltraWelfare/59a369896dc6ffb1c474451ff8119e2a to your computer and use it in GitHub Desktop.
Save UltraWelfare/59a369896dc6ffb1c474451ff8119e2a to your computer and use it in GitHub Desktop.
Grab mean color of screen in python instantly
import mss
from PIL import Image, ImageStat
# From what monitor to take screenshot
monitor_index = 0
def get_color(rescale=(0, 0)):
# Returns a list with the RGBA values.
# Add a rescale tuple parameter (x,y) other than 0,0 to make faster calculations
with mss.mss() as sct:
# Grab raw pixels of the screen with sct.
sct_img = sct.grab(sct.monitors[monitor_index])
# Convert to PIL Image to resize it to a lower resolution for faster calculations.
img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
if rescale != (0, 0):
img = img.resize(rescale)
# Use the ImageStat module to get the mean value.
return ImageStat.Stat(img).mean
@UltraWelfare
Copy link
Author

Thanks to /u/tjarko from reddit for bringing ImageStat to my attention!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment