杰瑞科技汇

Python如何实现屏幕捕获?

Of course! Capturing the screen in Python is a common task, and there are several excellent libraries to choose from. The best one depends on your specific needs: cross-platform compatibility, performance, video recording, or simplicity.

Python如何实现屏幕捕获?-图1
(图片来源网络,侵删)

Here's a breakdown of the most popular methods, from the simplest to the most powerful.


Method 1: The Easiest & Most Popular - pyautogui

This is the go-to library for simple screen captures. It's cross-platform (Windows, macOS, Linux) and very easy to use.

Pros:

  • Extremely simple to use.
  • Cross-platform.
  • No complex installation (on macOS).

Cons:

Python如何实现屏幕捕获?-图2
(图片来源网络,侵删)
  • Slower than other methods.
  • Can be blocked by security software on some systems.
  • Doesn't capture the mouse cursor by default.

Installation

pip install pyautogui

Note for macOS: You might need to install XQuartz first if you don't have it.

brew install xquartz

Example Code

This code captures the entire screen and saves it as a PNG file.

import pyautogui
import time
# Give yourself 5 seconds to switch to the window you want to capture
print("Screen capture in 5 seconds...")
time.sleep(5)
# 1. Capture the entire screen
screenshot = pyautogui.screenshot()
# 2. Save the screenshot to a file
screenshot.save("fullscreen_screenshot.png")
print("Screenshot saved as fullscreen_screenshot.png")
# 3. Capture a specific region (left, top, width, height)
# For example, capture a 500x300 pixel area starting at (100, 200)
region_screenshot = pyautogui.screenshot(region=(100, 200, 500, 300))
region_screenshot.save("region_screenshot.png")
print("Region screenshot saved as region_screenshot.png")

Method 2: High Performance & Video - opencv-python + numpy

This combination is extremely fast and is the standard for applications that require high performance, like computer vision or recording video. It uses your system's underlying capture capabilities.

Pros:

Python如何实现屏幕捕获?-图3
(图片来源网络,侵删)
  • Very fast performance.
  • Excellent for capturing video frames.
  • Integrates seamlessly with OpenCV for image processing.

Cons:

  • Installation can be tricky on some systems (especially Windows).
  • Requires numpy.

Installation

pip install opencv-python numpy

Troubleshooting Windows: If the mss library (used internally) fails, you might need to install Visual C++ Build Tools.

Example Code

This code captures the screen using OpenCV and displays it in a window.

import cv2
import numpy as np
while True:
    # 1. Capture screen using OpenCV
    # The `0` is the screen index. For most setups, it's 0.
    # The `grab=True` makes it faster than grabbing the whole screen.
    screen = np.array(cv2.VideoCapture(0).read()[1])
    # 2. Display the screenshot
    cv2.imshow('Screen Capture', screen)
    # 3. Check for 'q' key press to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# 4. Clean up
cv2.destroyAllWindows()

Method 3: The Most Powerful & Flexible - mss (Multi-Screen Shot)

mss is a pure Python library with a C backend that is incredibly fast and flexible. It's often the preferred choice for performance-critical applications. It's the library that opencv-python often uses under the hood.

Pros:

  • Extremely fast and efficient.
  • Cross-platform.
  • Great for capturing multiple monitors.
  • Can easily capture specific regions.

Cons:

  • The API is slightly more low-level than pyautogui.

Installation

pip install mss

Example Code

This example captures the primary monitor and saves it.

import mss
import mss.tools
with mss.mss() as sct:
    # 1. Get information of the first monitor
    monitor_number = 1
    sct_img = sct.grab(sct.monitors[monitor_number])
    # 2. Save to the picture file
    mss.tools.to_png(sct_img.rgb, sct_img.size, output="monitor_1.png")
    print(f"Saved screenshot of monitor {monitor_number} to monitor_1.png")
    # 3. Capture a specific region
    # The region is a tuple: (left, top, width, height)
    region = {'top': 40, 'left': 0, 'width': 800, 'height': 640}
    sct_img = sct.grab(region)
    mss.tools.to_png(sct_img.rgb, sct_img.size, output="region_screenshot.png")
    print("Saved region screenshot to region_screenshot.png")

Method 4: macOS Only - cocoa / quartz

If you are only targeting macOS, you can use the built-in Quartz framework via PyObjC. This gives you direct access to the operating system's most efficient screen capture functions.

Pros:

  • Potentially the fastest method on macOS.
  • Native access to all macOS features.

Cons:

  • macOS only.
  • Requires pyobjc-core.

Installation

pip install pyobjc-core pyobjc-framework-Quartz

Example Code

This code captures the main display using native macOS APIs.

from Quartz import CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowImageDefault
from Quartz import CGWindowListCreateImage, CGRectInfinite, kCGWindowListOptionOnScreenOnly
from AppKit import NSImage
import time
def capture_screen():
    # Get a list of all windows on screen
    window_list = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID)
    # Find the main display window (usually the first one with a large size)
    main_display = None
    for window in window_list:
        if window.get('kCGWindowBounds', {}).get('Height') > 1000: # Heuristic for main display
            main_display = window
            break
    if not main_display:
        print("Could not find main display window.")
        return None
    window_id = main_display['kCGWindowNumber']
    image_ref = CGWindowListCreateImage(
        CGRectInfinite,
        kCGWindowListOptionIncludingWindow,
        window_id,
        kCGWindowImageDefault
    )
    if image_ref:
        # Convert the Core Graphics image to a PyObjC NSImage
        ns_image = NSImage.alloc().initWithCGImage_(image_ref)
        return ns_image
    else:
        print("Failed to capture screen.")
        return None
# --- Main execution ---
if __name__ == '__main__':
    print("Capturing screen in 3 seconds...")
    time.sleep(3)
    screenshot = capture_screen()
    if screenshot:
        # Save the screenshot to a file
        screenshot TIFFRepresentationToFile("macos_screenshot.tiff", True)
        print("Screenshot saved as macos_screenshot.tiff")

Summary and Recommendation

Library Best For Performance Platform Key Feature
pyautogui Simplicity & Quick Scripts Low Cross-Platform Easiest to use.
mss High Performance & Video High Cross-Platform Fastest, great for regions.
opencv-python Computer Vision & Video High Cross-Platform Integrates with CV.
cocoa/Quartz Maximum Performance on macOS Very High macOS Only Native access.

My Recommendation:

  • For a quick and simple script that just needs to take a picture of the screen, use pyautogui.
  • For any application that needs to be fast, especially if you're capturing video or many frames per second, use mss. It's the modern, best-in-class choice for this task.
  • If you're doing image processing with OpenCV anyway, using opencv-python is a great choice.
分享:
扫描分享到社交APP
上一篇
下一篇