识图自动点击软件,图片识别连点器,自动识别图片点击脚本

7 阅读1分钟

下载地址:m.pan38.com/download.ph… 提取码:6666

项目包含三个主要模块:主程序模块(image_clicker.py)负责核心的图像识别和点击功能,配置文件处理模块(config_loader.py)管理模板配置,图形用户界面模块(gui.py)提供友好的操作界面。使用时需要安装opencv-python、pyautogui、pillow等依赖库。

 import cv2 import numpy as np import pyautogui import time import argparse from PIL import ImageGrab from threading import Thread, Event class ImageClicker: def __init__(self, template_path, interval=1.0, confidence=0.8): self.template = cv2.imread(template_path, cv2.IMREAD_COLOR) if self.template is None: raise ValueError(f"无法加载模板图片: {template_path}") self.interval = interval self.confidence = confidence self.stop_event = Event() self.template_height, self.template_width = self.template.shape[:2] def find_template(self, screenshot): result = cv2.matchTemplate(screenshot, self.template, cv2.TM_CCOEFF_NORMED) _, max_val, _, max_loc = cv2.minMaxLoc(result) if max_val >= self.confidence: top_left = max_loc bottom_right = (top_left[0] + self.template_width, top_left[1] + self.template_height) center_x = (top_left[0] + bottom_right[0]) // 2 center_y = (top_left[1] + bottom_right[1]) // 2 return (center_x, center_y), max_val return None, max_val def run(self): print(f"开始监控,间隔: {self.interval}秒,置信度: {self.confidence}") try: while not self.stop_event.is_set(): screenshot = np.array(ImageGrab.grab()) screenshot = cv2.cvtColor(screenshot, cv2.COLOR_RGB2BGR) position, confidence = self.find_template(screenshot) if position: print(f"找到目标 (置信度: {confidence:.2f}),点击位置: {position}") pyautogui.moveTo(position[0], position[1]) pyautogui.click() time.sleep(self.interval) except KeyboardInterrupt: print("\n监控已停止") def start(self): self.thread = Thread(target=self.run) self.thread.start() def stop(self): self.stop_event.set() self.thread.join() def main(): parser = argparse.ArgumentParser(description="图片识别自动点击器") parser.add_argument("template", help="模板图片路径") parser.add_argument("-i", "--interval", type=float, default=1.0, help="检查间隔(秒)") parser.add_argument("-c", "--confidence", type=float, default=0.8, help="匹配置信度(0-1)") args = parser.parse_args() clicker = ImageClicker(args.template, args.interval, args.confidence) print("按Ctrl+C停止程序") try: clicker.run() except KeyboardInterrupt: clicker.stop() if __name__ == "__main__": main()

import json import os class ClickerConfig: def __init__(self, config_path="config.json"): self.config_path = config_path self.default_config = { "templates": [], "default_interval": 1.0, "default_confidence": 0.8, "click_delay": 0.2, "move_duration": 0.5 } self.config = self.load_config() def load_config(self): if os.path.exists(self.config_path): try: with open(self.config_path, 'r') as f: return json.load(f) except json.JSONDecodeError: print("配置文件损坏,使用默认配置") return self.default_config return self.default_config def save_config(self): with open(self.config_path, 'w') as f: json.dump(self.config, f, indent=4) def add_template(self, template_path, name=None): if not os.path.exists(template_path): raise FileNotFoundError(f"模板文件不存在: {template_path}") template = { "path": template_path, "name": name or os.path.basename(template_path), "interval": self.config["default_interval"], "confidence": self.config["default_confidence"] } self.config["templates"].append(template) self.save_config() def get_templates(self): return self.config["templates"] def remove_template(self, index): if 0 <= index < len(self.config["templates"]): self.config["templates"].pop(index) self.save_config() return True return False 

tkinter as tk from tkinter import ttk, filedialog, messagebox from PIL import Image, ImageTk import cv2 from config_loader import ClickerConfig from image_clicker import ImageClicker import threading class AutoClickerGUI: def __init__(self, root): self.root = root self.root.title("图片识别自动点击器") self.config = ClickerConfig() self.clicker = None self.running = False self.setup_ui() self.load_templates() def setup_ui(self): # 主框架 main_frame = ttk.Frame(self.root, padding="10") main_frame.pack(fill=tk.BOTH, expand=True) # 模板列表 template_frame = ttk.LabelFrame(main_frame, text="模板列表", padding="10") template_frame.pack(fill=tk.BOTH, expand=True, side=tk.LEFT) self.template_list = ttk.Treeview(template_frame, columns=("name", "path"), show="headings") self.template_list.heading("name", text="名称") self.template_list.heading("path", text="路径") self.template_list.pack(fill=tk.BOTH, expand=True) # 控制按钮 btn_frame = ttk.Frame(template_frame) btn_frame.pack(fill=tk.X, pady=5) ttk.Button(btn_frame, text="添加模板", command=self.add_template).pack(side=tk.LEFT, padx=5) ttk.Button(btn_frame, text="删除模板", command=self.remove_template).pack(side=tk.LEFT, padx=5) # 预览区域 preview_frame = ttk.LabelFrame(main_frame, text="模板预览", padding="10") preview_frame.pack(fill=tk.BOTH, expand=True, side=tk.RIGHT) self.preview_label = ttk.Label(preview_frame) self.preview_label.pack(fill=tk.BOTH, expand=True) # 控制面板 control_frame = ttk.LabelFrame(main_frame, text="控制面板", padding="10") control_frame.pack(fill=tk.X, pady=10) ttk.Label(control_frame, text="检查间隔(秒):").grid(row=0, column=0, sticky=tk.W) self.interval_var = tk.DoubleVar(value=self.config.config["default_interval"]) ttk.Entry(control_frame, textvariable=self.interval_var).grid(row=0, column=1, sticky=tk.W) ttk.Label(control_frame, text="置信度(0-1):").grid(row=1, column=0, sticky=tk.W) self.confidence_var = tk.DoubleVar(value=self.config.config["default_confidence"]) ttk.Entry(control_frame, textvariable=self.confidence_var).grid(row=1, column=1, sticky=tk.W) self.start_btn = ttk.Button(control_frame, text="开始", command=self.toggle_clicker) self.start_btn.grid(row=2, column=0, columnspan=2, pady=5) # 绑定事件 self.template_list.bind("<>", self.show_preview) def load_templates(self): for item in self.template_list.get_children(): self.template_list.delete(item) for template in self.config.get_templates(): self.template_list.insert("", tk.END, values=(template["name"], template["path"])) def add_template(self): file_path = filedialog.askopenfilename( title="选择模板图片", filetypes=[("图片文件", "*.png;*.jpg;*.jpeg;*.bmp")] ) if file_path: name = filedialog.asksaveasfilename( title="为模板命名", initialfile=os.path.basename(file_path), defaultextension=".png" ) try: self.config.add_template(file_path, os.path.basename(name)) self.load_templates() except Exception as e: messagebox.showerror("错误", str(e)) def remove_template(self): selection = self.template_list.selection() if selection: index = self.template_list.index(selection[0]) if self.config.remove_template(index): self.load_templates() self.preview_label.config(image="") def show_preview(self, event): selection = self.template_list.selection() if selection: path = self.template_list.item(selection[0])["values"][1] try: img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = Image.fromarray(img) img.thumbnail((300, 300)) photo = ImageTk.PhotoImage(img) self.preview_label.config(image=photo) self.preview_label.image = photo except Exception as e: print(f"加载预览失败: {e}") def toggle_clicker(self): if self.running: self.stop_clicker() else: self.start_clicker() def start_clicker(self): selection = self.template_list.selection() if not selection: messagebox.showwarning("警告", "请先选择一个模板") return index = self.template_list.index(selection[0]) template = self.config.get_templates()[index] try: self.clicker = ImageClicker( template["path"], float(self.interval_var.get()), float(self.confidence_var.get()) ) self.thread = threading.Thread(target=self.clicker.run) self.thread.daemon = True self.running = True self.thread.start() self.start_btn.config(text="停止") except Exception as e: messagebox.showerror("错误", str(e)) def stop_clicker(self): if self.clicker: self.clicker.stop() self.running = False self.start_btn.config(text="开始") def on_closing(self): self.stop_clicker() self.root.destroy() if __name__ == "__main__": root = tk.Tk() app = AutoClickerGUI(root) root.protocol("WM_DELETE_WINDOW", app.on_closing) root.mainloop()