python - 如何通过 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")
解决方案
如果你只想要文本,检查图标,当它找到它时,用相对于图标的坐标拍摄整个盒子的照片(你很容易得到这个,因为 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")
推荐阅读
- r - 如何替换 R 中日期对象中的日期?
- c# - 移动焦点而不是选择 wpf 数据网格的 keydown
- python - 当 WebDriver 实例从 conftest.py (Python + Selenium) 传递给测试类时,无法访问 WebDriver 类的方法
- angular - Angular 9 TypeError:无法读取未定义的属性“订阅”
- curl - 将本地文件上传到 url 的正确 curl 命令
- algorithm - GLSL Vulkan compute shader to efficiently prune zeros from a shared array to make a compressed array
- gulp - 似乎无法在我的 Windows 10 机器上全局安装 gulp
- redux - 在 node.js 后端导入问题
- c# - async/await 通过重新启动已经执行的代码表现得很奇怪
- sql-server - 从多个连接表中删除行