carbonx commited on
Commit
4585960
·
verified ·
1 Parent(s): 9f45f5e

Add screen_capture.py

Browse files
Files changed (1) hide show
  1. screen_capture.py +46 -0
screen_capture.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fast cross-platform screen capture using mss (desktop) or PIL fallback (headless)."""
2
+ import numpy as np
3
+ from PIL import Image
4
+
5
+
6
+ def capture_primary_monitor() -> Image.Image:
7
+ """Capture the primary monitor and return a PIL RGB Image."""
8
+ try:
9
+ import mss
10
+ with mss.mss() as sct:
11
+ monitor = sct.monitors[1] # primary monitor
12
+ screenshot = sct.grab(monitor)
13
+ img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
14
+ return img
15
+ except Exception:
16
+ # Fallback for headless/server environments
17
+ img = Image.new("RGB", (1280, 720), color=(30, 30, 46))
18
+ return img
19
+
20
+
21
+ def capture_all_monitors() -> Image.Image:
22
+ """Capture all monitors combined."""
23
+ try:
24
+ import mss
25
+ with mss.mss() as sct:
26
+ monitor = sct.monitors[0] # all monitors
27
+ screenshot = sct.grab(monitor)
28
+ img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
29
+ return img
30
+ except Exception:
31
+ img = Image.new("RGB", (1280, 720), color=(30, 30, 46))
32
+ return img
33
+
34
+
35
+ def capture_region(top: int, left: int, width: int, height: int) -> Image.Image:
36
+ """Capture a specific region."""
37
+ try:
38
+ import mss
39
+ with mss.mss() as sct:
40
+ region = {"top": top, "left": left, "width": width, "height": height}
41
+ screenshot = sct.grab(region)
42
+ img = Image.frombytes("RGB", screenshot.size, screenshot.bgra, "raw", "BGRX")
43
+ return img
44
+ except Exception:
45
+ img = Image.new("RGB", (width, height), color=(30, 30, 46))
46
+ return img