53 lines
1.7 KiB
Python
53 lines
1.7 KiB
Python
import os
|
|
import glob
|
|
from PIL import Image
|
|
|
|
|
|
def get_latest_screenshot(directory, ext='jpg'):
|
|
"""Return the latest file path with the given extension in directory or None if none found."""
|
|
if not directory:
|
|
return None
|
|
if not os.path.isdir(directory):
|
|
return None
|
|
pattern = os.path.join(directory, f'*.{ext}')
|
|
files = glob.glob(pattern)
|
|
if not files:
|
|
return None
|
|
return max(files, key=os.path.getctime)
|
|
|
|
|
|
def process_image(image_path):
|
|
"""Return 'open', 'closed' or 'unknown' based on average brightness of an image.
|
|
|
|
The function is defensive and returns 'unknown' if the path is missing or an error occurs.
|
|
"""
|
|
if not image_path or not os.path.isfile(image_path):
|
|
return 'unknown'
|
|
try:
|
|
with Image.open(image_path) as img:
|
|
img = img.convert('RGB')
|
|
img = img.resize((2, 2))
|
|
pixels = list(img.getdata())
|
|
if not pixels:
|
|
return 'unknown'
|
|
avg = [sum(ch) / len(pixels) for ch in zip(*pixels)]
|
|
luminance = sum(avg) / 3.0
|
|
return 'closed' if luminance < 128 else 'open'
|
|
except Exception:
|
|
return 'unknown'
|
|
|
|
|
|
def get_brightness(image_path):
|
|
"""Return average brightness (0-255) as float, or None on error."""
|
|
if not image_path or not os.path.isfile(image_path):
|
|
return None
|
|
try:
|
|
with Image.open(image_path) as img:
|
|
img = img.convert('L')
|
|
img = img.resize((16, 16))
|
|
pixels = list(img.getdata())
|
|
if not pixels:
|
|
return None
|
|
return float(sum(pixels) / len(pixels))
|
|
except Exception:
|
|
return None |