使用OpenCV实现Python脚本连续抓取屏幕并显示

问题描述 投票:0回答:1

我想实时捕获我的在线游戏并在玩家姓名上创建矩形框并使用 OCR 读取这些姓名。实现代码后,我面临多个屏幕的错误。屏幕的无限镜像正在发生。请求您提供有关代码的帮助。

import cv2
import numpy as np
from PIL import ImageGrab
import pytesseract

# Set the path to the Tesseract executable (change this if necessary)
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Set the coordinates for the selected rectangular area
x, y, width, height = 100, 100, 300, 100

while True:
    # Capture the screen frame
    screenshot = ImageGrab.grab()

    # Convert the screenshot to an OpenCV image
    frame = np.array(screenshot)

    # Extract the selected rectangular area
    selected_area = frame[y:y+height, x:x+width]

    # Convert the selected area to grayscale
    gray_image = cv2.cvtColor(selected_area, cv2.COLOR_BGR2GRAY)

    # Apply thresholding to enhance text visibility
    _, thresholded = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

    # Perform OCR on the thresholded image
    player_name = pytesseract.image_to_string(thresholded)

    # Display the captured frame and OCR result
    cv2.imshow("Screen Capture", frame)
    cv2.imshow("Selected Area", selected_area)
    print("Detected Player Name:", player_name.strip())

    # Check for the 'q' key to exit the loop
    if cv2.waitKey(1) == ord('q'):
        break

# Release resources and close windows
cv2.destroyAllWindows()

我尝试使用不同的代码集,但仍然面临问题。请求您的帮助。

python computer-vision ocr
1个回答
0
投票

“多屏误差”和“无限镜像”是什么意思?

此外,您还需要在循环末尾添加一个

time.sleep
,您的 CPU 在这里压力太大了。

我觉得1秒的等待时间已经足够满足你的需求了!

© www.soinside.com 2019 - 2024. All rights reserved.