import cv2 import numpy as np import pyautogui import tkinter as tk from PIL import ImageTk, Image class WindowDetector: def __init__(self, template_path): self.template = cv2.imread(template_path, 0) self.w, self.h = self.template.shape[::-1] def detect(self): screenshot = pyautogui.screenshot() screenshot = np.array(screenshot) screenshot = cv2.cvtColor(screenshot, cv2.COLOR_BGR2GRAY) res = cv2.matchTemplate(screenshot, self.template, cv2.TM_CCOEFF_NORMED) threshold = 0.8 loc = np.where(res >= threshold) for pt in zip(*loc[::-1]): cv2.rectangle(screenshot, pt, (pt[0] + self.w, pt[1] + self.h), (0, 0, 255), 2) return screenshot class App: def __init__(self, template_path): self.window_detector = WindowDetector(template_path) self.root = tk.Tk() self.root.title("Window Detector") self.root.geometry("800x600") self.canvas = tk.Canvas(self.root, width=800, height=600) self.canvas.pack() self.template = ImageTk.PhotoImage(Image.open(template_path)) tk.Button(self.root, text="Detect", command=self.detect_window).pack() tk.Label(self.root, image=self.template).pack() self.root.mainloop() def detect_window(self): screenshot = self.window_detector.detect() img = ImageTk.PhotoImage(Image.fromarray(screenshot)) self.canvas.create_image(0, 0, anchor=tk.NW, image=img) self.root.update_idletasks() if __name__ == "__main__": app = App("template.png")
时间: 2024-04-27 15:24:52 浏览: 175
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
这段代码是用来检测屏幕上是否存在一个特定的窗口,它首先读取一个模板图像,然后使用pyautogui库截取屏幕图像。接着,它使用OpenCV中的模板匹配算法来在屏幕截图中寻找模板图像的匹配位置。如果匹配程度超过了设定的阈值,就会在屏幕截图中标出匹配的位置。最后,它使用tkinter库创建了一个GUI窗口,其中包含一个按钮和一个标签,用户可以点击按钮来检测屏幕上是否存在指定的窗口,并在标签中显示检测结果。
阅读全文