import cv2
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import numpy as np
import datetime
class Application(tk.Tk):
def __init__(self):
super().__init__()
self.title("Camera_Match")
self.geometry("800x600")
# 初始化全局变量
self.ix, self.iy = -1, -1
self.roi_set = False
self.roi = None
self.drawing = False
self.template_loaded = False
self.match_done = False
self.template = None
self.method = tk.StringVar(value="cv2.TM_CCOEFF_NORMED") # 默认匹配方法
self.results_text = ""
self.matches = []
self.match_status = tk.StringVar(value="等待开始")
# 打开摄像头
self.cap = cv2.VideoCapture(0)
# 创建主画布
self.canvas = tk.Canvas(self, width=640, height=480)
self.canvas.pack(side=tk.TOP, padx=10, pady=10)
# 创建状态标签
self.status_label = tk.Label(self, textvariable=self.match_status, font=("Arial", 16), fg="red")
self.status_label.pack(side=tk.TOP)
# 创建退出按钮
self.quit_button = tk.Button(self, text="退出", command=self.quit)
self.quit_button.pack(side=tk.TOP, padx=10, pady=10)
# 创建选择框
self.method_frame = tk.Frame(self)
self.method_frame.pack(side=tk.TOP, padx=10, pady=10)
self.method_label = tk.Label(self.method_frame, text="匹配方法:")
self.method_label.pack(side=tk.LEFT, padx=5)
methods = [
("模板匹配", "cv2.TM_CCOEFF_NORMED"),
("矩阵归一化", "cv2.normalize"),
("矩阵归一化33", "cv2.normalize"),
("寻找最值", "cv2.minMaxLoc")
]
for text, mode in methods:
b = tk.Radiobutton(self.method_frame, text=text, variable=self.method, value=mode, command=self.select_method)
b.pack(side=tk.LEFT)
# 创建用于显示操作记录和匹配结果的区域
self.results_frame = tk.Frame(self)
self.results_frame.pack(side=tk.TOP, fill=tk.X, padx=10, pady=10)
self.results_label = tk.Label(self.results_frame, text="操作记录与匹配结果:")
self.results_label.pack(side=tk.TOP, padx=5, pady=5)
self.results_textbox = tk.Text(self.results_frame, wrap='word', height=10, width=40)
self.results_textbox.pack(side=tk.TOP, padx=5, pady=5)
# 绑定鼠标事件
self.canvas.bind("<ButtonPress-1>", self.on_button_press)
self.canvas.bind("<B1-Motion>", self.on_mouse_motion)
self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
# 启动摄像头读取和显示循环
self.update_frame()
def select_method(self):
self.results_text += f"选择了匹配方法:{self.method.get()}\n"
self.update_results_text()
def on_button_press(self, event):
self.drawing = True
self.ix, self.iy = event.x, event.y
def on_mouse_motion(self, event):
if self.drawing:
self.canvas.delete("rect")
self.canvas.create_rectangle(min(self.ix, event.x), min(self.iy, event.y),
max(self.ix, event.x), max(self.iy, event.y),
outline="green", tag="rect")
def on_button_release(self, event):
if self.drawing:
self.drawing = False
self.canvas.delete("rect")
self.ix, self.iy = min(self.ix, event.x), min(self.iy, event.y)
self.roi = self.frame[min(self.iy, event.y):max(self.iy, event.y),
min(self.ix, event.x):max(self.ix, event.x)]
self.roi_set = True
self.template = self.roi
self.results_text += f"选择了区域:({min(self.ix, event.x)}, {min(self.iy, event.y)}) -> ({max(self.ix, event.x)}, {max(self.iy, event.y)})\n"
self.update_results_text()
self.match_status.set("匹配中")
def update_results_text(self):
self.results_textbox.delete(1.0, tk.END)
self.results_textbox.insert(tk.END, self.results_text)
def update_frame(self):
ret, frame = self.cap.read()
if ret:
frame = cv2.flip(frame, 1) # 镜像翻转图像
# 确保 frame 是一个有效的 numpy 数组
self.frame = frame.copy() # 使用 .copy() 来避免引用问题
# 如果已经设置了 ROI,则进行模板匹配
if self.roi_set and self.template is not None and self.template.size > 0:
method = eval(self.method.get())
if method == cv2.TM_CCOEFF_NORMED:
template = cv2.cvtColor(self.template, cv2.COLOR_BGR2GRAY)
w, h = template.shape[::-1]
res = cv2.matchTemplate(cv2.cvtColor(self.frame, cv2.COLOR_BGR2GRAY), template, method)
threshold = 0.8
loc = np.where(res >= threshold)
matches = list(zip(*loc[::-1]))
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
self.matches.clear()
if len(matches) > 0:
for pt in matches:
cv2.rectangle(self.frame, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
self.results_text += f"{current_time} 匹配位置: {pt}, 匹配度: {res[pt[1], pt[0]]:.2f}\n"
self.matches.append(True)
self.match_status.set("匹配完成")
else:
self.match_status.set("匹配失败")
self.update_results_text()
# 将OpenCV BGR格式转换为Tkinter PhotoImage格式
frame_tk = self.cv_to_tk(self.frame)
self.canvas.create_image(0, 0, anchor=tk.NW, image=frame_tk)
self.canvas.image = frame_tk
# 更新并重复调用
self.after(30, self.update_frame)
@staticmethod
def cv_to_tk(image_cv):
image_cv_rgb = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)
image_pil = Image.fromarray(image_cv_rgb)
return ImageTk.PhotoImage(image_pil)
if __name__ == "__main__":
app = Application()
app.mainloop()
# 释放资源
app.cap.release()