给上面的代码添加上 在屏幕上绘制出识别的图片周围绿线
时间: 2023-12-11 22:05:39 浏览: 221
HuoyanDemo.rar_android开发_Java_
可以使用cv2.rectangle()函数在屏幕截图中标出匹配位置并绘制绿色矩形框。具体来说,可以在WindowDetector类的detect()函数中加入以下代码:
```
for pt in zip(*loc[::-1]):
cv2.rectangle(screenshot, pt, (pt[0] + self.w, pt[1] + self.h), (0, 255, 0), 2)
```
这段代码会在屏幕截图中标出匹配位置,并使用绿色的线条绘制矩形框。完整的代码如下:
```
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, 255, 0), 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")
```
这样,运行程序后点击“Detect”按钮即可在屏幕截图中标出匹配位置并绘制绿色矩形框。
阅读全文