Skip to content

Instantly share code, notes, and snippets.

@angelospanag
Last active February 21, 2023 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angelospanag/39b881a667e5edc5eb877f0c02218d53 to your computer and use it in GitHub Desktop.
Save angelospanag/39b881a667e5edc5eb877f0c02218d53 to your computer and use it in GitHub Desktop.
Screenshot a window on Windows and OCR using Python and Tesseract
"""
Requires installation of Tesseract for Windows: https://github.com/UB-Mannheim/tesseract/wiki
"""
import pyautogui
import pytesseract
import win32gui
# Get the handle of the window you want to capture
window_handle = win32gui.FindWindow(None, "Task Manager")
# Get the position and size of the window
window_rect = win32gui.GetWindowRect(window_handle)
window_pos_x = window_rect[0]
window_pos_y = window_rect[1]
window_width = window_rect[2] - window_rect[0]
window_height = window_rect[3] - window_rect[1]
# Take a screenshot of the window
screenshot = pyautogui.screenshot(
region=(window_pos_x, window_pos_y, window_width, window_height)
)
text = pytesseract.image_to_string(screenshot)
print(text)
# Save the screenshot to a file
screenshot.save("screenshot.png")
[tool.poetry]
name = "test-screenshot"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
readme = "README.md"
packages = [{include = "test_screenshot"}]
[tool.poetry.dependencies]
python = "^3.11"
pyautogui = "^0.9.53"
pywin32 = "^305"
pillow = "^9.4.0"
pytesseract = "^0.3.10"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment