首页 > 解决方案 > 如何通过 Pyautogui 自动随机拍摄截图

问题描述

目标我想从图像中提取文本。我玩了一个随机出现图标的游戏,并且从右边的图标附近有一个文本(文本作为图像)。我希望脚本只截取文本区域的屏幕截图。所以,每次他定位屏幕时我都想要脚本,我想让他截取文本的屏幕截图。这是理解这个想法的图像: 在此处输入图像描述

这是我的代码:

import pyautogui as py
import time
from PIL import Image
from pytesseract import *

pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'

while 1:
        indice1 = py.locateOnScreen("icon.png")
    
    if indice1:
        
        print("indice see it ")

        myScreenshot = py.screenshot()
        myScreenshot.save(r'C:\Users\rachidel07\Desktop\ok\venv\image.png')

        img=Image.open("image.png")
        output = pytesseract.image_to_string(img)
        print(output)

    else:
            print ("non")
        


标签: pythonpositionscreenshotpyautoguiregion

解决方案


如果你只想要文本,检查图标,当它找到它时,用相对于图标的坐标拍摄整个盒子的照片(你很容易得到这个,因为 locateonscreen 返回坐标,你可以测量有多大文本框是并进行数学运算。)然后使用 PIL 仅裁剪文本,然后使用 tesseract 进行 ocr。

要裁剪文本,您可以使用 PIL 中的 crop()。

from PIL import Image    

img = Image.open("image.png")
newimg = img.crop((100, 100, 150, 150))

newimg.save("croppedimage.png")

推荐阅读