import os import os import json from pathlib import Path from tqdm import tqdm import matplotlib.pyplot as plt from matplotlib.patches import Circle from openai import OpenAI import base64 import numpy as np import cv2 from PIL import Image, ImageTk import glob import ast import json import tkinter as tk from tkinter import filedialog, messagebox def parse_input(input_str): """ 将类似 "1, 2, (3, 4)" 的字符串转换为 [1, 2, [3, 4]] """ # 去除首尾空格 s = input_str.strip() # 如果字符串不以中括号开头和结尾,则自动包装成列表 if not (s.startswith('[') and s.endswith(']')): s = "[" + s + "]" # 将圆括号转换为中括号 s = s.replace('(', '[').replace(')', ']') try: result = ast.literal_eval(s) return result except Exception as e: print(f"解析错误: {e}") return None # ======= 以下为界面类代码 ======= import tkinter as tk from tkinter import filedialog, messagebox class VideoInterface: def __init__(self, root): self.root = root self.root.title("视频分割数据集审核工具") # self.root.geometry("1200x1000") # 默认帧率设置 self.default_fps = 20 # 播放视频的帧率 self.delay = int(1000 / self.default_fps) # 每帧延时(毫秒) # 数据集信息 self.video_dirs = [] # 存放每个视频的文件夹路径 self.current_video_index = -1 # 当前视频索引 self.approved_videos = [] # 存放用户批准的视频路径 self.colors = {1: (255, 0, 0), 2: (0, 255, 0), 3: (0, 0, 255), 4: (0, 255, 255), 5: (255, 255, 0), 6: (255, 0, 255), 7: (255, 255, 255), } # 创建界面控件 self.canvas = tk.Canvas(root, width=1000, height=600, bg="black") self.canvas.grid(row=0, column=0, columnspan=7, pady=10) # 控制按钮区域 self.btn_frame = tk.Frame(root) self.btn_frame.grid(row=1, column=0, columnspan=7, pady=1) self.info_label = tk.Label(self.btn_frame, text="加载数据集", font=("Arial", 12)) self.info_label.grid(row=0, column=0, padx=1, pady=1) self.load_btn = tk.Button(self.btn_frame, text="加载数据集", command=self.load_dataset) self.load_btn.grid(row=0, column=1, padx=1, pady=1) self.next_btn = tk.Button(self.btn_frame, text="下一视频", command=self.next_video, state=tk.DISABLED) self.next_btn.grid(row=0, column=2, padx=1, pady=1) self.previous_btn = tk.Button(self.btn_frame, text="上一个视频", command=self.previous_video, state=tk.DISABLED) self.previous_btn.grid(row=0, column=3, padx=1, pady=1) self.end_btn = tk.Button(self.btn_frame, text="结束审核", command=self.end_review, state=tk.DISABLED) self.end_btn.grid(row=0, column=4, padx=1, pady=1) self.replay_btn = tk.Button(self.btn_frame, text="回放", command=self.replay_video, state=tk.DISABLED) self.replay_btn.grid(row=0, column=5, padx=1, pady=1) self.pause_btn = tk.Button(self.btn_frame, text="暂停", command=self.pause_video, state=tk.DISABLED) self.pause_btn.grid(row=0, column=6, padx=1, pady=1) self.resume_btn = tk.Button(self.btn_frame, text="恢复", command=self.resume_video, state=tk.DISABLED) self.resume_btn.grid(row=0, column=7, padx=1, pady=1) self.target_label = tk.Label(self.btn_frame, text="物体索引") self.target_label.grid(row=0, column=8, padx=1) self.annotated_objects = tk.Text(self.btn_frame, width=20, height=3) self.annotated_objects.grid(row=0, column=9, padx=1) self.process_btn = tk.Button(self.btn_frame, text="caption", command=self.process_caption) self.process_btn.grid(row=0, column=10, padx=1) # 目标选择区域 self.target_frame = tk.Frame(root) self.target_frame.grid(row=2, column=0, columnspan=7, pady=1) self.caption_gpt4_text = tk.Text(self.target_frame, width=100, height=4) self.caption_gpt4_text.grid(row=0, column=0, columnspan=3, padx=1, pady=1) self.caption_gpt4_video_text = tk.Text(self.target_frame, width=100, height=4) self.caption_gpt4_video_text.grid(row=1, column=0, columnspan=3, padx=1, pady=1) self.caption_qwen_text = tk.Text(self.target_frame, width=100, height=4) self.caption_qwen_text.grid(row=2, column=0, columnspan=3, pady=1) self.caption_text = tk.Text(self.target_frame, width=100, height=4) self.caption_text.grid(row=3, column=0, columnspan=3, pady=1) self.confirm_caption_btn = tk.Button(self.target_frame, text="确认修改", command=self.confirm_caption) self.confirm_caption_btn.grid(row=4, column=0, padx=3, pady=1) self.confirm_video_btn = tk.Button(self.target_frame, text="该视频审核通过", command=self.confirm_video) self.confirm_video_btn.grid(row=4, column=1, padx=3, pady=1) self.result_dict = dict() # 播放相关变量 self.frames = [] # 当前视频中所有帧(存放文件路径) self.masks = [] # 当前视频中所有 mask(存放文件路径) self.frame_rate = 0 # 当前视频帧率 self.current_frame_index = 0 # 当前帧的索引 self.playing = False # 播放标志 self.photo = None # 保存 PhotoImage 避免被垃圾回收 def process_caption(self): self.obj_id = self.obj_id_list[self.current_exp_id] gpt4 = [] qwen = [] gpt4_video = [] for exp_id, exp in self.exp_dict.items(): if exp["obi_id"] == self.obj_id: gpt4.append(exp["gpt4o_exp"]) gpt4_video.append(exp["gpt4o_video_exp"]) qwen.append(exp["qwen_exp"]) self.gpt4 = gpt4 self.qwen = qwen self.gpt4_video = gpt4_video self.caption_gpt4_text.delete("1.0", tk.END) self.caption_gpt4_text.insert(tk.END, "gpt4: " + str(gpt4)) self.caption_gpt4_video_text.delete("1.0", tk.END) self.caption_gpt4_video_text.insert(tk.END, "gpt4_video: " + str(gpt4_video)) self.caption_qwen_text.delete("1.0", tk.END) self.caption_qwen_text.insert(tk.END, "qwen-vl: " + str(qwen)) self.current_exp_id += 1 def confirm_caption(self): """ 用户点击“确认修改”按钮后调用: 读取文本框中的修改后的 caption,解析后将当前待处理项写入字典, 然后更新 pending_index 并处理下一项(如果有)。 """ modified_caption = self.caption_text.get("1.0", tk.END).strip() try: import re responses = re.sub(r"'s", "\\'s", modified_caption) if not responses.endswith("']"): responses = responses.replace("]", "']") if not responses.startswith("['"): responses = responses.replace("[", "['") gpt_responses_list = ast.literal_eval(responses) except Exception as e: messagebox.showerror("错误", f"Caption格式错误:{e}") return # obj_id = self.pending_video_info["obj_id"] for num, res in enumerate(gpt_responses_list): self.exp_dict_[self.exp_index] = {"human_exp": res, "gpt4o_exp": self.gpt4[num], "obj_id": self.obj_id, "gpt4o_video_exp": self.gpt4_video[num], "qwen_exp": self.qwen[num], } self.exp_index += 1 # video_name = self.pending_video_info["video_name"] # self.video_dict[video_name] = { # "expressions": self.exp_dict, # "vid_id": self.pending_video_info["vid_id"], # "height": self.pending_video_info["height"], # "width": self.pending_video_info["width"], # } messagebox.showinfo("提示", "Caption已确认并保存。") # 处理下一个待处理项 # self.pending_index += 1 # if self.pending_index < len(self.pending_items): # self.process_next_pending_item() # else: # messagebox.showinfo("提示", "所有待处理目标均已确认。") def confirm_video(self): self.result_dict[self.current_video_name] = { "expressions": self.exp_dict_, "frames": self.video_dict[self.current_video_name]['frames'], "vid_id": self.video_dict[self.current_video_name]["vid_id"], "height": self.video_dict[self.current_video_name]["height"], "width": self.video_dict[self.current_video_name]["width"], } messagebox.showinfo("提示", "该视频审核通过") def load_dataset(self): """选择数据集根目录,每个子文件夹视为一个视频""" json_path = filedialog.askopenfilename(title="选择视频列表.json", filetypes=[("Text Files", "*.json")]) if not json_path: return f = open(json_path, 'r') video_dict = json.load(f)["videos"] self.video_dict = video_dict self.base_video_dir = "/Users/gongsitong/Desktop/dataset_processing/Ref_LVOS/JPEGImages" self.base_mask_dir = "/Users/gongsitong/Desktop/dataset_processing/Ref_LVOS/Annotations" video_json = "/Users/gongsitong/Desktop/dataset_processing/Ref_LVOS/video_exp_2.json" f = open(video_json, 'r') video_dict_ = json.load(f)["videos"] video_name_ = [video_name for video_name in video_dict_.keys()] # self.video_name_list = sorted([video_name for video_name in video_dict.keys() if video_name not in video_name_]) self.video_name_list = [video_name for video_name in video_dict.keys() if video_name not in video_name_] self.current_video_index = -1 self.approved_videos = [] self.info_label.config(text=f"共加载 {len(self.video_name_list)} 个视频文件夹") self.next_btn.config(state=tk.NORMAL) # self.approve_btn.config(state=tk.NORMAL) # self.summary_btn.config(state=tk.NORMAL) self.end_btn.config(state=tk.NORMAL) # 允许点击结束按钮 self.replay_btn.config(state=tk.DISABLED) # 初始时回放按钮不可用 self.previous_btn.config(state=tk.DISABLED) # 初始时“上一个视频”按钮不可用 # 自动播放第一个视频 self.next_video() def next_video(self): """切换到下一个视频""" self.playing = False # 停止当前视频的播放 self.current_video_index += 1 if self.current_video_index >= len(self.video_name_list): messagebox.showinfo("提示", "没有更多视频了!") return # 显示该视频对应的expression的输出 current_video_name = self.video_name_list[self.current_video_index] exp_dict = self.video_dict[current_video_name]["expressions"] self.current_video_name = current_video_name self.exp_dict = exp_dict self.current_exp_id = 0 obj_id_set = [] obj_id_ = "" for _, exp in exp_dict.items(): obj_id = exp['obj_id'] if obj_id_ != obj_id: obj_id_ = obj_id else: continue obj_id_set.append(obj_id) # obj_id_set = set(obj_id_set) self.obj_id_list = obj_id_set self.exp_dict_ = dict() self.exp_index = 0 self.annotated_objects.delete("1.0", tk.END) self.annotated_objects.insert(tk.END, str(obj_id_set)) current_video_path = os.path.join(self.base_video_dir, current_video_name) current_mask_path = os.path.join(self.base_mask_dir, current_video_name) self.masks = [os.path.join(current_mask_path, mask_name) for mask_name in os.listdir(current_mask_path)] self.masks.sort() self.info_label.config( text=f"视频 {self.current_video_index+1}/{len(self.video_name_list)}: {os.path.basename(current_video_path)}" ) self.current_video_path = current_video_path self.current_mask_path = current_mask_path # 获取帧图像与 mask 的文件列表(假定帧为 .jpg,mask 为 .png),并按名称排序 frame_files = sorted(glob.glob(os.path.join(current_video_path, "*.jpg"))) if current_video_path.split("/")[-3] == "LongVOS": mask_files = sorted(glob.glob(os.path.join(current_mask_path, "*.png"))) if not frame_files or not mask_files: messagebox.showerror("错误", f"在 {current_video_path} 中未找到足够的图像或 mask 文件!") self.next_video() return # 计算实际的帧数(根据帧率不同,进行调整) self.frames = frame_files # [:total_frames] if current_video_path.split("/")[-3] == "LongVOS": self.masks = mask_files# [:total_frames] self.current_frame_index = 0 # self.caption_text.delete("1.0", tk.END) # self.caption_text.insert(tk.END, exp_dict) # 开始播放当前视频 self.playing = True self.play_video() self.previous_btn.config(state=tk.NORMAL) # 启用“上一个视频”按钮 # -------------- 新增:启动视频后启用“暂停”,禁用“恢复” -------------- self.pause_btn.config(state=tk.NORMAL) self.resume_btn.config(state=tk.DISABLED) # --------------------------------------------------------- def previous_video(self): """跳转到上一个视频""" if self.current_video_index <= 0: messagebox.showinfo("提示", "已经是第一个视频了,无法回退!") return self.current_video_index -= 1 self.frames = [] # 清空帧数据 self.masks = [] # 清空mask数据 self.current_frame_index = 0 self.playing = False # 停止当前视频播放 self.next_video() # 载入并播放上一个视频 def play_video(self): """按照设定帧率循环播放视频""" if not self.playing: return if self.current_frame_index >= len(self.frames): # 播放结束 self.playing = False self.replay_btn.config(state=tk.NORMAL) # 显示回放按钮 return # 读取当前帧和对应的 mask frame_path = self.frames[self.current_frame_index] frame = cv2.imread(frame_path) frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) # processing the gt mask if frame_path.split("/")[-4] == "SAV": mask_list = [] for mask_path_ in self.masks: mask_path_list = [os.path.join(mask_path_, d) for d in os.listdir(mask_path_)] mask_path_list.sort() mask_list.append(mask_path_list[self.current_frame_index]) for num, mask_name in enumerate(mask_list): mask = Image.open(mask_name) gt_mask = np.array(mask) mask = (gt_mask > 0).astype(np.uint8) * 255 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: x, y, w, h = cv2.boundingRect(contour) cv2.rectangle(frame, (x, y), (x + w, y + h), self.colors[num + 1], 3) else: mask_path = self.masks[self.current_frame_index] mask = Image.open(mask_path) gt_mask_ = np.array(mask) anno_ids = np.unique(gt_mask_) for anno_id in range(1, len(anno_ids)): tmp_masks = np.zeros_like(gt_mask_) tmp_masks[gt_mask_ == anno_id] = 1 gt_mask = tmp_masks gt_mask[gt_mask == 255] = 0 mask = (gt_mask > 0).astype(np.uint8) * 255 # 变成 0 或 255 contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) for contour in contours: x, y, w, h = cv2.boundingRect(contour) # 获取 bbox 坐标 cv2.rectangle(frame, (x, y), (x + w, y + h), self.colors[anno_id], 3) # 蓝色 bbox img = Image.fromarray(frame) if frame is None or mask is None: self.current_frame_index += 1 self.root.after(self.delay, self.play_video) return # 将图像调整为 Canvas 大小 canvas_width = self.canvas.winfo_width() canvas_height = self.canvas.winfo_height() if canvas_width > 0 and canvas_height > 0: img = img.resize((canvas_width, canvas_height)) self.photo = ImageTk.PhotoImage(img) self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo) self.current_frame_index += 1 self.root.after(self.delay, self.play_video) def replay_video(self): """回放当前视频""" self.replay_btn.config(state=tk.DISABLED) # 禁用回放按钮 self.current_frame_index = 0 # 重置帧索引 self.playing = True self.play_video() # 重新开始播放视频 # -------------- 新增:启动视频后启用“暂停”,禁用“恢复” -------------- self.pause_btn.config(state=tk.NORMAL) self.resume_btn.config(state=tk.DISABLED) # --------------------------------------------------------- # --------------- 以下两个方法为新增的暂停与恢复功能 --------------- def pause_video(self): """暂停视频播放(新增)""" if self.playing: self.playing = False self.pause_btn.config(state=tk.DISABLED) self.resume_btn.config(state=tk.NORMAL) def resume_video(self): """恢复视频播放(新增)""" if not self.playing: self.playing = True self.resume_btn.config(state=tk.DISABLED) self.pause_btn.config(state=tk.NORMAL) self.play_video() # -------------------------------------------------------------- # def approve_video(self): # """标记当前视频为通过""" # if self.current_video_index < len(self.video_dirs): # current_video_path = self.video_dirs[self.current_video_index] # if current_video_path not in self.approved_videos: # self.approved_videos.append(current_video_path) # messagebox.showinfo("提示", f"视频 {os.path.basename(current_video_path)} 已批准!") # def show_summary(self): # """弹出对话框,显示所有已批准的视频,并保存为.txt文件""" # if not self.approved_videos: # messagebox.showinfo("总结", "当前没有任何视频被批准。") # return # # 保存已批准的视频路径到.txt文件 # summary_file = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text Files", "*.txt")]) # if not summary_file: # return # with open(summary_file, 'w') as f: # for video in self.approved_videos: # f.write(video + "\n") # summary_text = "已批准的视频:\n" + "\n".join(self.approved_videos) # messagebox.showinfo("总结", summary_text) def end_review(self): """结束审核并保存已批准的视频名称""" # if not self.approved_videos: # messagebox.showinfo("总结", "没有批准的视频,结束审核失败!") # return # 新增功能:将 self.video_dict 保存为 JSON 文件 json_file = filedialog.asksaveasfilename(title="保存结果JSON", defaultextension=".json", filetypes=[("JSON files", "*.json")]) output_dict = dict() output_dict['videos'] = self.result_dict if json_file: try: with open(json_file, 'w', encoding="utf-8") as f_json: json.dump(output_dict, f_json, indent=4, ensure_ascii=False) messagebox.showinfo("提示", f"已成功保存视频字典为 JSON 文件:{json_file}") except Exception as e: messagebox.showerror("错误", f"保存 JSON 文件失败:{e}") self.root.quit() # 退出程序 if __name__ == "__main__": root = tk.Tk() app = VideoInterface(root) root.mainloop()