| """Fast cross-platform screen capture using mss (desktop) or PIL fallback (headless).""" |
| import numpy as np |
| from PIL import Image |
|
|
|
|
| def capture_primary_monitor() -> Image.Image: |
| """Capture the primary monitor and return a PIL RGB Image.""" |
| try: |
| import mss |
| with mss.mss() as sct: |
| monitor = sct.monitors[1] |
| screenshot = sct.grab(monitor) |
| img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX") |
| return img |
| except Exception: |
| |
| img = Image.new("RGB", (1280, 720), color=(30, 30, 46)) |
| return img |
|
|
|
|
| def capture_all_monitors() -> Image.Image: |
| """Capture all monitors combined.""" |
| try: |
| import mss |
| with mss.mss() as sct: |
| monitor = sct.monitors[0] |
| screenshot = sct.grab(monitor) |
| img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX") |
| return img |
| except Exception: |
| img = Image.new("RGB", (1280, 720), color=(30, 30, 46)) |
| return img |
|
|
|
|
| def capture_region(top: int, left: int, width: int, height: int) -> Image.Image: |
| """Capture a specific region.""" |
| try: |
| import mss |
| with mss.mss() as sct: |
| region = {"top": top, "left": left, "width": width, "height": height} |
| screenshot = sct.grab(region) |
| img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX") |
| return img |
| except Exception: |
| img = Image.new("RGB", (width, height), color=(30, 30, 46)) |
| return img |
|
|