Skip to content
Projets

À propos

🚀 䞓䞺 Python 自劚化打造的高性胜截囟库 | 180+ FPS | 支持后台/遮挡 | 可暂停 零功耗埅机;🚀 High-performance capture library for Python automation | 180+ FPS | Background/Occluded Support | Pausable (Pause/Resume) Zero-Power Standby

Productivité et automatisation

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

wgc_python

English | 简䜓䞭文

PyPI Python License

🚀 䞺 Python 自劚化而生的窗口捕获库
高垧率捕获 · 零资源埅机 · 无视遮挡 · API 极简


䞺什么选择 wgc_python

🎯 䞓䞺自劚化场景讟计

䜠是吊圚䞺以䞋问题困扰

  • mss/BitBlt无法捕获被遮挡或后台窗口
  • PrintWindow性胜瓶颈固定 26ms+ 延迟
  • 其他 WGC 封装持续运行占甚资源频繁启停匀销巚倧50ms+

wgc_python 通过 Pause/Resume 机制解决了这䞪矛盟

# 䌠统方匏芁么持续空蜬浪莹资源芁么频繁启停承受延迟
start_capture()  # 50ms 匀销
get_frame()      # 获取截囟
stop_capture()   # 销毁䌚话50ms
# 䞋次截囟又芁重新匀始...

# wgc_python 方匏䞀次启劚按需截囟零匀销埅机
with WindowCapture("窗口", "类名") as cap:
    while running:
        frame = cap.capture_one()  # auto Resume → 等埅垧 → 拷莝 → Pause
        # 倄理囟像...

📊 性胜对比

方案 FPS 后台捕获 CPU 占甚 频繁切换匀销 暂停后 GPU 占甚
python-mss / BitBlt ~60 ❌ 高 䜎 N/A (无暂停抂念)
PrintWindow ~38 ✅ äž­ 䜎 N/A (每次调甚即捕获)
其他 WGC 封装 高 ✅ 高持续空蜬 高 (启停䌚话匀销倧) 高 (无法真正暂停)
wgc_python 高 ✅ 极䜎Pause时園零 极䜎原子标志䜍 園零无 D3D 操䜜

衚䞭䞺定性对比具䜓数倌因硬件、窗口内容䞎场景而匂建议以自己的实测䞺准。

✹ 栞心䌘势

1. 高垧率

  • WGC 盎接捕获 GPU 合成蟓出䞍逐垧截屏垧率䞊限远高于 PrintWindow 等 GDI 方案
  • 双猓冲 Staging 纹理GPU 匂步拷莝读写互䞍阻塞
  • 零拷莝友奜np.ndarray(strides=...) 盎接从 GPU 映射内存构造视囟

2. 智胜资源管理

  • Pause/Resume 蜯暂停䞍销毁䞍重建 WGC session仅原子标志䜍跳过垧倄理
  • capture_one() 自劚管理Resume → 等埅垧 → 拷莝 → Pause闎隙 GPU 驱劚零匀销
  • 䌚话倍甚避免频繁创建/销毁 D3D 讟倇的匀销

3. 极简 API

  • capture_one()䞀行代码完成按需捕获返回 numpy 数组
  • get_frame()零拷莝裞指针路埄高级䜿甚
  • 线皋安党C++ 层倄理所有倚线皋倍杂性

4. 倚匀并发

  • 同䞀进皋内可同时创建倚䞪捕获䌚话互䞍干扰
  • 每䞪䌚话独立 D3D11 讟倇 + 独立纹理 + 独立 WinRT session完党隔犻
  • 支持同窗口倚路并发捕获

5. 客户区粟准裁剪默讀䞍截取标题栏/蟹框

  • 默讀 client_area_only=True只捕获窗口客户区内容自劚裁剪标题栏和蟹框盎接蟓出有效像玠
  • 讟眮 client_area_only=False捕获敎䞪窗口含标题栏和蟹框满足 UI 记圕场景
  • DPI 感知自劚修正高 DPI 猩攟偏移裁剪粟床像玠级
  • GPU 级裁剪CopySubresourceRegion 圚 GPU 䞊完成裁剪䞍浪莹垊宜和 CPU

6. 光标捕获匀关

  • 默讀 capture_cursor=True画面包含錠标光标䞎垞规圕屏行䞺䞀臎
  • 讟眮 capture_cursor=False画面䞍含錠标指针适合自劚化 / 数据采集场景也可甚 set_cursor_capture_enabled() 运行时切换
  • 需 Windows 10 2004 (19041) 及以䞊系统旧系统自劚応略该选项

7. 无视遮挡

  • 支持捕获被遮挡、最小化、后台窗口
  • 完矎适配枞戏、桌面应甚等各种场景

快速匀始

安装

已发垃至 PyPI盎接 pip 安装即可

pip install wgc_python

基础甚法

from wgc_python import WindowCapture, enumerate_windows

# 枚䞟所有窗口
for title, class_name in enumerate_windows():
    print(f"{title} ({class_name})")

# 按需捕获掚荐 —— 零匀销埅机
with WindowCapture("窗口标题", "窗口类名") as cap:
    frame = cap.capture_one()     # BGRA numpy 数组shape (h, w, 4)
    if frame is not None:
        print(f"捕获成功: {frame.shape}")

# 客户区裁剪挔瀺
# 默讀 client_area_only=True只截取客户区䞍含标题栏/蟹框
cap_client = WindowCapture("记事本", "Notepad")                      # 只截内容
cap_full  = WindowCapture("记事本", "Notepad", client_area_only=False)  # 含标题栏
frame_client = cap_client.capture_one()  # 只有猖蟑区
frame_full  = cap_full.capture_one()    # 含标题栏 + 菜单 + 猖蟑区
cap_client.close()
cap_full.close()

# 䞍捕获錠标光标默讀 capture_cursor=True保持旧版行䞺
cap = WindowCapture("记事本", "Notepad", capture_cursor=False)
frame = cap.capture_one()               # 画面䞍含錠标指针
cap.set_cursor_capture_enabled(True)    # 也支持运行时切换
cap.close()

自劚化最䜳实践

from wgc_python import WindowCapture

cap = WindowCapture("枞戏窗口", "UnityWndClass")

while True:
    frame = cap.capture_one(timeout=1.0)
    if frame is not None:
        # frame 是 BGRA numpy 数组盎接甚于 OpenCV/暡板匹配
        pass
    time.sleep(1)

cap.close()

星瀺噚捕获掚荐党屏枞戏场景䜿甚

捕获目标窗口所圚的星瀺噚而非窗口本身捕获䌚话绑定星瀺噚目标窗口圚党屏/窗口之闎切换䞍䌚䜿捕获䌚话倱效窗口捕获暡匏䞋歀场景䌚冻结于最后䞀垧。

from wgc_python import WindowCaptureMonitor

# 定䜍目标窗口所圚的星瀺噚并捕获其党郚内容无客户区裁剪
cap = WindowCaptureMonitor("枞戏窗口", "UnityWndClass")
frame = cap.capture_one()   # 敎屏 BGRA åž§
cap.close()

适甚场景党屏枞戏的长期自劚化采集、目标窗口星瀺暡匏频繁变化的场景。需芁裁剪客户区或排陀其他窗口内容时仍请䜿甚 WindowCapture。

零拷莝高级甚法

from wgc_python import WindowCapture
import numpy as np
import ctypes

with WindowCapture("窗口", "类名") as cap:
    cap.resume()
    r = cap.get_frame()  # (ptr, w, h, row_pitch) — GPU 映射裞指针
    if r:
        ptr, w, h, rp = r
        arr = np.ndarray((h, w, 4), dtype=np.uint8,
                         buffer=(ctypes.c_ubyte * (h * rp)).from_address(ptr),
                         strides=(rp, 4, 1))
        # arr 是 GPU 内存的零拷莝视囟
        cap.release_frame()
    cap.pause()

实时星瀺

from wgc_python import WindowCapture
import cv2

with WindowCapture("窗口标题", "窗口类名") as cap:
    while True:
        frame = cap.capture_one()
        if frame is not None:
            cv2.imshow("Capture", cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()

API 参考

from wgc_python import (
    WindowCapture,             # 窗口捕获类䞊䞋文管理噚支持
    enumerate_windows,         # 枚䞟所有可见窗口
    get_last_error,            # 获取最后错误信息线皋安党
    get_active_capture_count,  # 获取掻跃捕获数
)

# WindowCapture 类方法:
#   cap = WindowCapture(title, class_name, client_area_only=True, capture_cursor=True)
#
#   cap.capture_one(timeout=0.5)  -> np.ndarray | None  ★ 掚荐
#      自劚 Resume → 等埅垧 → 拷莝䞺 numpy → Pause
#      捕获闎隙 WGC 完党䌑眠GPU 驱劚零匀销
#
#   cap.get_frame()              -> (ptr, w, h, row_pitch) | None
#   cap.release_frame()           # 释攟 GPU 映射
#   cap.pause()                   # 暂停捕获零资源埅机
#   cap.resume()                  # 恢倍捕获
#   cap.set_cursor_capture_enabled(enabled)  # 运行时切换光标捕获
#   cap.stop()                    # 停止垧到蟟
#   cap.close()                   # 销毁䌚话
#   cap.is_capturing()  -> bool
#   cap.is_paused()     -> bool
#   cap.get_frame_count()  -> int
#   cap.handle             -> int (DLL handle)

技术架构

WGC捕获 → GPU Surface纹理
              │
     ┌────────▌────────┐
     │  FrameArrived    │
     │  if pausing → ↑  │  ← Pause时盎接返回零 D3D 操䜜
     └────────┬─────────┘
              │
         CopyResource (GPU匂步倍制)
              ↓
    ┌─────────────────────────┐
    │  双猓冲Staging纹理       │
    │  [0] 写入 ←→ [1] 读取   │
    │  m_textureInUse 防冲撞   │
    └─────────────────────────┘
              ↓
         Map (氞久映射 GPU 内存)
              ↓
    ┌────── 零拷莝蟓出 ───────┐
    │ get_frame()              │
    │ 返回裞指针 → numpy零拷莝  │
    │ 需手劚 release_frame()    │
    └──────────────────────────┘

    ┌────── 䞀键捕获 ──────────┐
    │ capture_one()            │
    │ auto Pause/Resume        │
    │ 返回 numpy 数组          │
    │ 问隙 GPU 驱劚零匀销      │
    └──────────────────────────┘

Pause/Resume 工䜜原理

  甚户调甚 cap.pause()
         │
    m_isPaused = true   ◄──── 原子标志䜍埮秒级
    m_readableStagingIndex = -1
         │
    ┌────▌────────────────────────────────────────────┐
    │                FrameArrived 回调WGC 仍䌚觊发  │
    │                                                  │
    │  lock(mutex);                                    │
    │  if (m_isPaused) return;     // ← 纯CPU刀断跳过│
    │  // ↓ 以䞋只圚 resume 后执行 ↓                   │
    │  CopyResource(staging, frame);                   │
    │  m_readableStagingIndex = idx;                   │
    │  unlock(mutex);                                  │
    └────▲────────────────┬───────────────────────────┘
         │                │
  甚户调甚 cap.resume()  MapFrame 检查 readableStagingIndex
  m_isPaused = false      <0 → 最近垧尚未就绪返回 false
  
  䞍销毁 WGC session / 䞍重建 D3D 讟倇 / 䞍重新泚册回调
  → 恢倍零延迟无突刺

文件结构

wgc_python/
├── wgc_python/                   # Python 包
│   ├── __init__.py               # Python APIctypes FFI
│   └── wgc_python.dll            # 猖译后的 DLL
├── wgc_python_dll/               # C++ DLL 项目
│   ├── WGCWindowCapture.h/cpp    # WGC 捕获栞心双猓冲 + 零拷莝
│   ├── WGCExport.h/cpp           # DLL 富出含线皋安党错误倄理
│   ├── D3DInterop.cpp            # D3D11 讟倇互操䜜
│   ├── WindowEnumerator.h/cpp    # 窗口枚䞟
│   ├── pch.h                     # 预猖译倎
│   └── packages/                 # NuGet 包
├── test.py                       # 功胜测试
├── demon.py                      # 倚线皋实时星瀺瀺䟋
├── pyproject.toml                # pip 构建配眮
├── BUILD.md / BUILD_EN.md        # 构建诎明䞭/英
├── README.md / README_EN.md      # 䜿甚文档䞭/英
├── CONTRIBUTING.md               # 莡献指南
├── CODE_OF_CONDUCT.md            # 行䞺准则
├── LICENSE                       # MIT 讞可证
└── requirements.txt              # Python 䟝赖

系统芁求

  • Windows 10 1903+ (Build 18362)光标捕获匀关需 2004+ (Build 19041)
  • Python 3.8+

构建 DLL

诊见 BUILD.md


故障排陀

问题 解决方案
DLL 未扟到 确保 wgc_python.dll 圚正确䜍眮
捕获倱莥 检查窗口是吊可见Windows 版本 >= 1903
䞭文路埄保存倱莥 䜿甚 cv2.imencode + open().write() 代替 cv2.imwrite
䟝赖猺倱 pip install numpy opencv-python

适甚场景

  • ✅ 枞戏 AI / 自劚化脚本
  • ✅ RPA 流皋自劚化
  • ✅ 屏幕圕制 / 盎播
  • ✅ UI 自劚化测试
  • ✅ 计算机视觉应甚

鞣谢

本项目基于 robmikh/Win32CaptureSample 匀发。


License

MIT License


English

🎯 Designed for Automation Scenarios

Are you struggling with these problems?

  • mss/BitBlt: Cannot capture occluded or background windows
  • PrintWindow: Performance bottleneck, fixed 26ms+ latency
  • Other WGC wrappers: Continuous resource consumption, huge overhead for frequent start/stop (50ms+)

wgc_python solves this dilemma with its Pause/Resume mechanism:

# Traditional approach: Either waste resources or suffer latency
start_capture()  # 50ms overhead
get_frame()      # Get screenshot
stop_capture()   # Destroy session (50ms)

# wgc_python approach: One-time init, on-demand capture, zero-overhead standby
with WindowCapture("Window", "Class") as cap:
    while running:
        frame = cap.capture_one()  # auto Resume → wait → copy → Pause
        # Process image...

📊 Performance Comparison

Solution FPS Background Capture CPU Usage Toggle Overhead GPU When Paused
python-mss / BitBlt ~60 ❌ High Low N/A (no pause)
PrintWindow ~38 ✅ Medium Low N/A (per-call)
Other WGC wrappers High ✅ High (continuous) High (session start/stop) High (can't truly pause)
wgc_python High ✅ Near Zero (when paused) Very Low (atomic flag) Zero (no D3D ops)

Qualitative comparison only; actual numbers vary by hardware, window content, and workload — benchmark on your own setup.

✹ Core Advantages

1. High Frame Rate

  • WGC captures GPU composition output directly instead of per-frame GDI screenshots — frame rate ceiling far above PrintWindow-style approaches
  • Double-buffered Staging Texture: GPU async copy, read/write non-blocking
  • Zero-copy path: np.ndarray(strides=...) directly from GPU-mapped memory

2. Smart Resource Management

  • Pause/Resume soft-pause: Atomic flag only, no WGC session teardown
  • capture_one() auto management: Resume → wait → copy → Pause, zero GPU driver overhead between captures
  • Session Reuse: No frequent D3D device creation/destruction

3. Minimalist API

  • capture_one(): One-line on-demand capture, returns numpy array
  • get_frame(): Zero-copy raw pointer path (advanced)
  • Thread safe: C++ handles all multi-threading complexity

4. Multi-Instance Capture

  • Create multiple capture sessions simultaneously within one process
  • Each session has its own D3D11 device, staging textures, and WinRT session — fully isolated
  • Supports concurrent capture of the same window

5. Client Area Precision (No Title Bar by Default)

  • Default client_area_only=True: captures only window client area, automatically crops title bar and borders
  • Set client_area_only=False: captures entire window including title bar and borders, for UI recording
  • DPI-aware: automatic high-DPI scaling correction for pixel-perfect cropping
  • GPU-level cropping via CopySubresourceRegion, no wasted bandwidth or CPU

6. Cursor Capture Toggle

  • Default capture_cursor=True: frame includes the mouse cursor, same as typical screen recording
  • Set capture_cursor=False: frame excludes the mouse pointer, ideal for automation / data collection (also toggleable at runtime via set_cursor_capture_enabled())
  • Requires Windows 10 2004 (19041) or later; silently ignored on older systems

7. Capture Behind Windows

  • Supports capturing occluded, minimized, and background windows
  • Perfect for games, desktop apps, and various scenarios

Quick Start

Installation

Published on PyPI — install directly with pip:

pip install wgc_python

Basic Usage

from wgc_python import WindowCapture, enumerate_windows

# Enumerate all windows
for title, class_name in enumerate_windows():
    print(f"{title} ({class_name})")

# On-demand capture (recommended — zero-resource standby)
with WindowCapture("Window Title", "WindowClass") as cap:
    frame = cap.capture_one()     # BGRA numpy array, shape (h, w, 4)
    if frame is not None:
        print(f"Captured: {frame.shape}")

# Client area demo
# Default client_area_only=True: content only, no title bar/borders
cap_client = WindowCapture("Notepad", "Notepad")                       # content only
cap_full  = WindowCapture("Notepad", "Notepad", client_area_only=False) # with title bar
frame_client = cap_client.capture_one()  # edit area only
frame_full  = cap_full.capture_one()    # title bar + menu + edit area
cap_client.close()
cap_full.close()

# Disable mouse cursor capture (default capture_cursor=True, same as previous versions)
cap = WindowCapture("Notepad", "Notepad", capture_cursor=False)
frame = cap.capture_one()               # frame does not contain the mouse pointer
cap.set_cursor_capture_enabled(True)    # runtime toggle is also supported
cap.close()

Best Practice for Automation

from wgc_python import WindowCapture

cap = WindowCapture("Game Window", "UnityWndClass")

while True:
    frame = cap.capture_one(timeout=1.0)
    if frame is not None:
        # frame is BGRA numpy array, ready for OpenCV/template matching
        pass
    time.sleep(1)

cap.close()

Zero-Copy Advanced Usage

from wgc_python import WindowCapture
import numpy as np
import ctypes

with WindowCapture("Window", "Class") as cap:
    cap.resume()
    r = cap.get_frame()  # (ptr, w, h, row_pitch) — GPU mapped pointer
    if r:
        ptr, w, h, rp = r
        arr = np.ndarray((h, w, 4), dtype=np.uint8,
                         buffer=(ctypes.c_ubyte * (h * rp)).from_address(ptr),
                         strides=(rp, 4, 1))
        # arr is a zero-copy view into GPU-mapped memory
        cap.release_frame()
    cap.pause()

Real-time Display

from wgc_python import WindowCapture
import cv2

with WindowCapture("Window Title", "WindowClass") as cap:
    while True:
        frame = cap.capture_one()
        if frame is not None:
            cv2.imshow("Capture", cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cv2.destroyAllWindows()

API Reference

from wgc_python import (
    WindowCapture,             # Window capture class (context manager support)
    enumerate_windows,         # Enumerate all visible windows
    get_last_error,            # Get last error message (thread-safe)
    get_active_capture_count,  # Get active capture count
)

# WindowCapture methods:
#   cap = WindowCapture(title, class_name, client_area_only=True, capture_cursor=True)
#
#   cap.capture_one(timeout=0.5)  -> np.ndarray | None  ★ recommended
#      Auto Resume → wait for frame → copy to numpy → Pause
#      WGC fully dormant between captures, zero GPU driver overhead
#
#   cap.get_frame()              -> (ptr, w, h, row_pitch) | None
#   cap.release_frame()           # Release GPU mapping
#   cap.pause()                   # Pause capture (zero-resource standby)
#   cap.resume()                  # Resume capture
#   cap.set_cursor_capture_enabled(enabled)  # Toggle cursor capture at runtime
#   cap.stop()                    # Stop frame arrival
#   cap.close()                   # Destroy session
#   cap.is_capturing()  -> bool
#   cap.is_paused()     -> bool
#   cap.get_frame_count()  -> int
#   cap.handle             -> int (DLL handle)

Technical Architecture

WGC Capture → GPU Surface Texture
                   │
         ┌─────────▌──────────┐
         │   FrameArrived     │
         │  if pausing → ↑   │  ← Paused: return directly, zero D3D ops
         └─────────┬──────────┘
                   │
              CopyResource (GPU async copy)
                   │
     ┌─────────────────────────────┐
     │  Double-buffered Staging    │
     │  [0] Write ←→ [1] Read      │
     │  m_textureInUse anti-collide │
     └─────────────────────────────┘
                   │
              Map (permanently mapped GPU memory)
                   │
     ┌────── Zero-Copy Output ────┐
     │ get_frame()                 │
     │ raw ptr → numpy zero-copy   │
     │ requires release_frame()    │
     └─────────────────────────────┘

     ┌────── One-Click Capture ───┐
     │ capture_one()               │
     │ auto Pause/Resume           │
     │ returns numpy array         │
     │ zero GPU overhead when idle │
     └─────────────────────────────┘

How Pause/Resume Works

  User calls cap.pause()
         │
    m_isPaused = true   ◄──── atomic flag, microsecond-level
    m_readableStagingIndex = -1
         │
    ┌────▌────────────────────────────────────────────┐
    │           FrameArrived Callback (WGC still fires)│
    │                                                  │
    │  lock(mutex);                                    │
    │  if (m_isPaused) return;     // ← pure CPU, skip│
    │  // ↓ below runs only after resume ↓             │
    │  CopyResource(staging, frame);                   │
    │  m_readableStagingIndex = idx;                   │
    │  unlock(mutex);                                  │
    └────▲────────────────┬───────────────────────────┘
         │                │
  User calls cap.resume()  MapFrame checks readableStagingIndex
  m_isPaused = false       <0 → no frame ready → returns false

  No WGC session destroy / no D3D device recreate / no callback re-register
  → zero-latency resume, no spikes

File Structure

wgc_python/
├── wgc_python/                   # Python package
│   ├── __init__.py               # Python API (ctypes FFI)
│   └── wgc_python.dll            # Compiled DLL
├── wgc_python_dll/               # C++ DLL Project
│   ├── WGCWindowCapture.h/cpp    # Capture core (double-buffered + zero-copy)
│   ├── WGCExport.h/cpp           # DLL exports (thread-safe error handling)
│   ├── D3DInterop.cpp            # D3D11 device interop
│   ├── WindowEnumerator.h/cpp    # Window enumeration
│   ├── pch.h                     # Precompiled header
│   └── packages/                 # NuGet packages
├── test.py                       # Functional tests
├── demon.py                      # Threaded realtime display example
├── pyproject.toml                # pip build config
├── BUILD.md / BUILD_EN.md        # Build instructions (CN/EN)
├── README.md / README_EN.md      # Usage docs (CN/EN)
├── CONTRIBUTING.md               # Contributing guide
├── CODE_OF_CONDUCT.md            # Code of conduct
├── LICENSE                       # MIT License
└── requirements.txt              # Python dependencies

Build DLL

See BUILD.md


Requirements

  • Windows 10 1903+ (Build 18362); cursor capture toggle requires 2004+ (Build 19041)
  • Python 3.8+

Troubleshooting

Issue Solution
DLL not found Ensure wgc_python.dll is in the correct location
Capture failed Check if window is visible, Windows version >= 1903
Non-ASCII path save failed Use cv2.imencode + open().write() instead of cv2.imwrite
Missing dependencies pip install numpy opencv-python

Use Cases

  • ✅ Game AI / Automation Scripts
  • ✅ RPA Process Automation
  • ✅ Screen Recording / Streaming
  • ✅ UI Automation Testing
  • ✅ Computer Vision Applications

Acknowledgments

This project is based on robmikh/Win32CaptureSample.


License

MIT License

Explorer des projets similaires

Chargement