-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscreen_region_trigger.py
More file actions
433 lines (348 loc) · 16.2 KB
/
Copy pathscreen_region_trigger.py
File metadata and controls
433 lines (348 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
"""
屏幕区域定时监控 + Windows BitBlt 截图
支持 PNG / JPEG 两种输出格式
自动查找并监控名为"相机"的窗口
"""
import ctypes
import ctypes.wintypes
import datetime
import os
import time
import mss.tools
from PIL import Image, ImageChops
# ──────────────────────────────────────────────
# ① 配置区域(按需修改)
# ──────────────────────────────────────────────
POLL_INTERVAL = 2.0 # 扫描间隔(秒)
DIFF_THRESHOLD = 3.0 # 差异阈值:超过此值视为"有变化"(%),正确的像素变化率
SAVE_DIR = r"E:\iflow\screen_cap\screenshots"
SAVE_FORMAT = "PNG" # 截图格式:PNG(无损)或 JPEG(有损压缩)
JPEG_QUALITY = 85 # SAVE_FORMAT=JPEG 时生效,1-100,越高越清晰/文件越大
TARGET_WINDOW_TITLE = "相机" # 要监控的窗口名称
# 节流配置
MIN_SAVE_INTERVAL = 5.0 # 两次截图之间的最小时间间隔(秒),避免频繁截图
# ──────────────────────────────────────────────
os.makedirs(SAVE_DIR, exist_ok=True)
# ── Windows API 结构体(BitBlt 全屏截图)────────────────
class BITMAPINFOHEADER(ctypes.Structure):
_fields_ = [
("biSize", ctypes.wintypes.DWORD),
("biWidth", ctypes.wintypes.LONG),
("biHeight", ctypes.wintypes.LONG),
("biPlanes", ctypes.wintypes.WORD),
("biBitCount", ctypes.wintypes.WORD),
("biCompression", ctypes.wintypes.DWORD),
("biSizeImage", ctypes.wintypes.DWORD),
("biXPelsPerMeter", ctypes.wintypes.LONG),
("biYPelsPerMeter", ctypes.wintypes.LONG),
("biClrUsed", ctypes.wintypes.DWORD),
("biClrImportant", ctypes.wintypes.DWORD),
]
class BITMAPINFO(ctypes.Structure):
_fields_ = [
("bmiHeader", BITMAPINFOHEADER),
("bmiColors", ctypes.c_ubyte * 4),
]
gdi32 = ctypes.WinDLL("gdi32", use_last_error=True)
user32 = ctypes.WinDLL("user32", use_last_error=True)
kernel32= ctypes.WinDLL("kernel32",use_last_error=True)
# ── 窗口查找函数 ──────────────────────────────────────
def find_window_by_title(title: str):
"""根据窗口标题查找窗口句柄"""
return user32.FindWindowW(None, title)
def get_window_rect(hwnd):
"""获取窗口的位置和大小"""
class RECT(ctypes.Structure):
_fields_ = [
("left", ctypes.wintypes.LONG),
("top", ctypes.wintypes.LONG),
("right", ctypes.wintypes.LONG),
("bottom", ctypes.wintypes.LONG),
]
rect = RECT()
if user32.GetWindowRect(hwnd, ctypes.byref(rect)):
return {
"left": rect.left,
"top": rect.top,
"width": rect.right - rect.left,
"height": rect.bottom - rect.top
}
return None
def get_client_rect(hwnd):
"""获取窗口客户区的位置和大小(不含标题栏)"""
class RECT(ctypes.Structure):
_fields_ = [
("left", ctypes.wintypes.LONG),
("top", ctypes.wintypes.LONG),
("right", ctypes.wintypes.LONG),
("bottom", ctypes.wintypes.LONG),
]
rect = RECT()
if user32.GetClientRect(hwnd, ctypes.byref(rect)):
# 获取客户区相对于屏幕的坐标
client_left = ctypes.wintypes.LONG(0)
client_top = ctypes.wintypes.LONG(0)
user32.ClientToScreen(hwnd, ctypes.byref(client_left), ctypes.byref(client_top))
return {
"left": client_left.value,
"top": client_top.value,
"width": rect.right - rect.left,
"height": rect.bottom - rect.top
}
return None
def find_camera_window():
"""查找相机窗口并返回其区域信息和窗口句柄"""
print(f"[screen_region_trigger] 正在查找窗口: '{TARGET_WINDOW_TITLE}'...")
hwnd = find_window_by_title(TARGET_WINDOW_TITLE)
if hwnd == 0:
print(f"[screen_region_trigger] 未找到窗口: '{TARGET_WINDOW_TITLE}'")
return None
# 获取窗口在屏幕上的位置
window_rect = get_window_rect(hwnd)
if not window_rect:
print(f"[screen_region_trigger] 无法获取窗口位置")
return None
# 处理全屏/高DPI情况下的负数坐标问题
window_left = max(0, window_rect["left"])
window_top = max(0, window_rect["top"])
# 获取客户区(不含标题栏)
client_rect = get_client_rect(hwnd)
if client_rect and client_rect["width"] > 0 and client_rect["height"] > 0:
# 客户区坐标需要加上窗口位置转换为屏幕坐标
screen_left = window_left + client_rect["left"]
screen_top = window_top + client_rect["top"]
# 确保坐标不为负数
screen_left = max(0, screen_left)
screen_top = max(0, screen_top)
print(f"[screen_region_trigger] 找到窗口客户区: left={screen_left}, top={screen_top}, w={client_rect['width']}, h={client_rect['height']}")
return {
"hwnd": hwnd,
"left": screen_left,
"top": screen_top,
"width": client_rect["width"],
"height": client_rect["height"]
}
# 如果客户区获取失败,使用整个窗口
if window_rect["width"] > 0 and window_rect["height"] > 0:
print(f"[screen_region_trigger] 找到窗口: left={window_left}, top={window_top}, w={window_rect['width']}, h={window_rect['height']}")
return {
"hwnd": hwnd,
"left": window_left,
"top": window_top,
"width": window_rect["width"],
"height": window_rect["height"]
}
return None
def windows_screenshot(left: int, top: int, width: int, height: int, save_path: str):
"""BitBlt 截取指定区域,以 PNG 或 JPEG 保存。"""
hdc_screen = user32.GetDC(0)
hdc_mem = gdi32.CreateCompatibleDC(hdc_screen)
hbmp = gdi32.CreateCompatibleBitmap(hdc_screen, width, height)
gdi32.SelectObject(hdc_mem, hbmp)
if not gdi32.BitBlt(hdc_mem, 0, 0, width, height,
hdc_screen, left, top, 0x00CC0020):
raise ctypes.WinError(ctypes.get_last_error())
bmi = BITMAPINFO()
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = width
bmi.bmiHeader.biHeight = -height # top-down DIB
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 24
bmi.bmiHeader.biCompression = 0
buf = ctypes.create_string_buffer(width * height * 3)
gdi32.GetDIBits(hdc_mem, hbmp, 0, height, buf, ctypes.byref(bmi), 0)
img = Image.frombytes("RGB", (width, height), buf.raw, "raw", "BGR")
if SAVE_FORMAT == "JPEG":
img.save(save_path, "JPEG", quality=JPEG_QUALITY)
else:
img.save(save_path, "PNG")
gdi32.DeleteObject(hbmp)
gdi32.DeleteDC(hdc_mem)
user32.ReleaseDC(0, hdc_screen)
return save_path
def windows_screenshot_to_image(left: int, top: int, width: int, height: int) -> Image.Image:
"""BitBlt 截取指定区域,返回 PIL Image 对象"""
hdc_screen = user32.GetDC(0)
hdc_mem = gdi32.CreateCompatibleDC(hdc_screen)
hbmp = gdi32.CreateCompatibleBitmap(hdc_screen, width, height)
gdi32.SelectObject(hdc_mem, hbmp)
if not gdi32.BitBlt(hdc_mem, 0, 0, width, height,
hdc_screen, left, top, 0x00CC0020):
raise ctypes.WinError(ctypes.get_last_error())
bmi = BITMAPINFO()
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = width
bmi.bmiHeader.biHeight = -height # top-down DIB
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 24
bmi.bmiHeader.biCompression = 0
buf = ctypes.create_string_buffer(width * height * 3)
gdi32.GetDIBits(hdc_mem, hbmp, 0, height, buf, ctypes.byref(bmi), 0)
img = Image.frombytes("RGB", (width, height), buf.raw, "raw", "BGR")
gdi32.DeleteObject(hbmp)
gdi32.DeleteDC(hdc_mem)
user32.ReleaseDC(0, hdc_screen)
return img
def bring_window_to_front(hwnd):
"""将窗口带到前台"""
user32.SetForegroundWindow(hwnd)
# 等待窗口置顶
time.sleep(0.1)
def window_screenshot(hwnd, width: int, height: int, save_path: str):
"""使用 PrintWindow 直接截取窗口内容(即使窗口被遮挡也能截取)"""
# 获取窗口DC
hdc_window = user32.GetDC(hwnd)
hdc_mem = gdi32.CreateCompatibleDC(hdc_window)
hbmp = gdi32.CreateCompatibleBitmap(hdc_window, width, height)
gdi32.SelectObject(hdc_mem, hbmp)
# 使用 PrintWindow API 截取窗口
# PW_CLIENTONLY = 0x00000001 表示只截取客户区
if not user32.PrintWindow(hwnd, hdc_mem, 0):
raise ctypes.WinError(ctypes.get_last_error())
bmi = BITMAPINFO()
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = width
bmi.bmiHeader.biHeight = -height # top-down DIB
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 24
bmi.bmiHeader.biCompression = 0
buf = ctypes.create_string_buffer(width * height * 3)
gdi32.GetDIBits(hdc_mem, hbmp, 0, height, buf, ctypes.byref(bmi), 0)
img = Image.frombytes("RGB", (width, height), buf.raw, "raw", "BGR")
if SAVE_FORMAT == "JPEG":
img.save(save_path, "JPEG", quality=JPEG_QUALITY)
else:
img.save(save_path, "PNG")
gdi32.DeleteObject(hbmp)
gdi32.DeleteDC(hdc_mem)
user32.ReleaseDC(hwnd, hdc_window)
return save_path
def window_screenshot_to_image(hwnd, width: int, height: int) -> Image.Image:
"""使用 PrintWindow 截取窗口内容,返回 PIL Image 对象"""
# 获取窗口DC
hdc_window = user32.GetDC(hwnd)
hdc_mem = gdi32.CreateCompatibleDC(hdc_window)
hbmp = gdi32.CreateCompatibleBitmap(hdc_window, width, height)
gdi32.SelectObject(hdc_mem, hbmp)
# 使用 PrintWindow API 截取窗口
# PW_CLIENTONLY = 0x00000001 表示只截取客户区
if not user32.PrintWindow(hwnd, hdc_mem, 0):
raise ctypes.WinError(ctypes.get_last_error())
bmi = BITMAPINFO()
bmi.bmiHeader.biSize = ctypes.sizeof(BITMAPINFOHEADER)
bmi.bmiHeader.biWidth = width
bmi.bmiHeader.biHeight = -height # top-down DIB
bmi.bmiHeader.biPlanes = 1
bmi.bmiHeader.biBitCount = 24
bmi.bmiHeader.biCompression = 0
buf = ctypes.create_string_buffer(width * height * 3)
gdi32.GetDIBits(hdc_mem, hbmp, 0, height, buf, ctypes.byref(bmi), 0)
img = Image.frombytes("RGB", (width, height), buf.raw, "raw", "BGR")
gdi32.DeleteObject(hbmp)
gdi32.DeleteDC(hdc_mem)
user32.ReleaseDC(hwnd, hdc_window)
return img
# ── 帧差计算(mss 快速采集)────────────────────────────
def capture_region_array(sct, region) -> Image.Image:
shot = sct.grab(region)
return Image.frombytes("RGB", shot.size, shot.rgb)
def diff_percent(img_a: Image.Image, img_b: Image.Image, thresh: int = 5) -> float:
"""计算两张图片的差异百分比(正确的像素级变化率)"""
# 确保图片尺寸一致
if img_a.size != img_b.size:
return 100.0
# 转换为灰度图比较(避免RGB通道重复计算问题)
gray_a = img_a.convert("L")
gray_b = img_b.convert("L")
# 计算绝对差值
diff = ImageChops.difference(gray_a, gray_b)
# 统计变化像素数
total_pixels = img_a.width * img_a.height
changed_pixels = sum(1 for pixel in diff.getdata() if pixel > thresh)
return (changed_pixels / total_pixels) * 100
# ── 主循环 ────────────────────────────────────────────
def main():
sct = mss.MSS()
fmt_display = "JPEG" if SAVE_FORMAT == "JPEG" else "PNG"
print(f"[screen_region_trigger] 扫描间隔: {POLL_INTERVAL}s | 变化阈值: {DIFF_THRESHOLD}%")
print(f"[screen_region_trigger] 截图格式: {fmt_display} | 保存目录: {SAVE_DIR}")
print("[screen_region_trigger] 按 Ctrl+C 停止\n")
# 持续查找相机窗口
reg = None
while reg is None:
reg = find_camera_window()
if reg is None:
print(f"[screen_region_trigger] 等待 {POLL_INTERVAL} 秒后重试...")
time.sleep(POLL_INTERVAL)
reg["mon"] = 1 # 添加显示器编号
print(f"[screen_region_trigger] 开始监控窗口区域: left={reg['left']}, top={reg['top']}, "
f"w={reg['width']}, h={reg['height']}\n")
shot_count = 0
last_save_time = 0 # 上次保存时间
oldscr = None # 上次保存的图片,初始为 None
while True:
# 检查窗口是否仍然存在
current_reg = find_camera_window()
if current_reg is None:
print(f"[screen_region_trigger] 窗口已关闭或移动,重新查找...")
reg = None
while reg is None:
reg = find_camera_window()
if reg is None:
print(f"[screen_region_trigger] 等待 {POLL_INTERVAL} 秒后重试...")
time.sleep(POLL_INTERVAL)
reg["mon"] = 1
print(f"[screen_region_trigger] 重新找到窗口: left={reg['left']}, top={reg['top']}, "
f"w={reg['width']}, h={reg['height']}")
# 重置 oldscr
oldscr = None
continue
time.sleep(POLL_INTERVAL)
# 使用屏幕截图(BitBlt)进行比较,确保获取实际显示内容
# 先将窗口置顶以确保截取到正确内容
if "hwnd" in reg and reg["hwnd"]:
bring_window_to_front(reg["hwnd"])
curr_img = windows_screenshot_to_image(
reg["left"], reg["top"], reg["width"], reg["height"]
)
current_time = time.time()
# 如果是首次截图,直接保存;否则比较与上次保存的图片差异
should_save = False
diff = 0.0
if oldscr is None:
# 首次截图,直接保存
should_save = True
else:
# 比较当前截图与 oldscr 的差异
diff = diff_percent(oldscr, curr_img)
# 如果差异超过阈值且满足时间间隔,则保存截图
if diff > DIFF_THRESHOLD:
should_save = True
if should_save:
if oldscr is None or current_time - last_save_time >= MIN_SAVE_INTERVAL:
now = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
ext = "jpg" if SAVE_FORMAT == "JPEG" else "png"
fname = os.path.join(SAVE_DIR, f"trigger_{now}_{shot_count:04d}.{ext}")
# 使用屏幕截图(BitBlt)保存,确保获取实际显示内容
try:
# 先将窗口置顶
if "hwnd" in reg and reg["hwnd"]:
bring_window_to_front(reg["hwnd"])
windows_screenshot(
reg["left"], reg["top"], reg["width"], reg["height"], fname
)
except Exception as e:
print(f"[错误] 保存图片失败: {e}")
fname = None
if fname:
shot_count += 1
last_save_time = current_time
# 更新 oldscr 为屏幕截图,确保下次比较一致
oldscr = windows_screenshot_to_image(
reg["left"], reg["top"], reg["width"], reg["height"]
)
print(f"[截屏] {fname} (diff={diff:.1f}%)")
else:
print(f"[提示] 检测到变化 ({diff:.1f}%),但距离上次截图不足 {MIN_SAVE_INTERVAL} 秒,跳过")
if __name__ == "__main__":
main()