import cv2 import numpy as np import tkinter as tk from PIL import ImageGrab class CaptureOverlay: def __init__(self, parent, output_path='template.png'): self.parent = parent self.output_path = output_path self.saved = False self.root = tk.Toplevel(parent) self.root.attributes('-fullscreen', True) self.root.attributes('-alpha', 0.3) self.root.configure(bg='black') self.root.wait_visibility() self.root.attributes('-topmost', True) self.start_x = self.start_y = None self.rect = None self.canvas = tk.Canvas(self.root, cursor='cross', highlightthickness=0) self.canvas.pack(fill='both', expand=True) self.canvas.bind('', self.on_press) self.canvas.bind('', self.on_drag) self.canvas.bind('', self.on_release) self.result = None self.parent.wait_window(self.root) def on_press(self, e): self.start_x, self.start_y = e.x, e.y self.rect = self.canvas.create_rectangle(e.x, e.y, e.x, e.y, outline='red', width=3) def on_drag(self, e): self.canvas.coords(self.rect, self.start_x, self.start_y, e.x, e.y) def on_release(self, e): x1 = min(self.start_x, e.x) y1 = min(self.start_y, e.y) x2 = max(self.start_x, e.x) y2 = max(self.start_y, e.y) w, h = x2 - x1, y2 - y1 if w < 10 or h < 10: self.root.destroy() return self.root.withdraw() self.root.update() img = ImageGrab.grab(bbox=(x1, y1, x2, y2)) img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR) self.saved = bool(cv2.imwrite(self.output_path, img)) self.root.destroy()