From ed636f68f64c84f6e0ffc23a4d0da40c637a7307 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Oct 2025 17:42:27 +0800 Subject: [PATCH 1/5] =?UTF-8?q?=E9=87=87=E9=9B=86=E5=8D=A1bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- preview.py | 72 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 60 insertions(+), 12 deletions(-) diff --git a/preview.py b/preview.py index da87660..ca89278 100644 --- a/preview.py +++ b/preview.py @@ -161,6 +161,10 @@ class PreviewWindow: def create_grid_window(self): """创建网格窗口""" + # 重新加载配置,确保获取最新值 + config_manager.load_config() + self.config = config_manager.config + # 获取显示配置 display = self.config.get('display', {}) preview_width = display.get('preview_width', 1000) @@ -168,6 +172,20 @@ class PreviewWindow: columns = display.get('preview_columns', 2) rows = display.get('preview_rows', 2) + # 验证配置值是否有效(防止读取到无效的小值) + if preview_width < 100 or preview_height < 100: + print(f"⚠️ 警告: 配置中的预览尺寸无效 ({preview_width}x{preview_height}),使用默认值") + preview_width = 1000 + preview_height = 700 + + if columns < 1 or columns > 10: + columns = 2 + if rows < 1 or rows > 10: + rows = 2 + + # 调试输出配置值 + print(f"📐 预览窗口配置: {preview_width}x{preview_height}, 网格: {columns}x{rows}") + root = tk.Tk() root.title("采集卡预览 - 点击放大") root.geometry(f"{preview_width}x{preview_height}") @@ -227,6 +245,10 @@ class PreviewWindow: texts_to_draw = [] frame_idx = 0 + # 确保至少有一些采集卡数据 + if not self.caps: + texts_to_draw.append((canvas_width // 2, canvas_height // 2, "未找到采集卡", 'red')) + for idx in self.caps.keys(): row = frame_idx // columns col = frame_idx % columns @@ -306,26 +328,52 @@ class PreviewWindow: canvas.delete("all") # 先绘制所有图像(底层) - if images_to_draw and self.debug_count <= 3: - print(f"✅ 准备绘制 {len(images_to_draw)} 个图像到画布 ({canvas_width}x{canvas_height})") + if self.debug_count <= 3: + print(f"📊 绘制状态: {len(images_to_draw)} 个图像, {len(texts_to_draw)} 个文本, 画布={canvas_width}x{canvas_height}") - for photo, x, y in images_to_draw: - try: - canvas.create_image(x, y, image=photo, anchor='center') - except Exception as e: - if "pyimage" not in str(e).lower(): - print(f"绘制图像错误: {e}") + if images_to_draw: + for i, (photo, x, y) in enumerate(images_to_draw): + try: + # 确保坐标在画布范围内 + if 0 <= x <= canvas_width and 0 <= y <= canvas_height: + canvas.create_image(x, y, image=photo, anchor='center') + if self.debug_count <= 3 and i == 0: + print(f" 绘制图像 #{i} 到位置 ({x}, {y})") + else: + if self.debug_count <= 3: + print(f" ⚠️ 图像 #{i} 位置 ({x}, {y}) 超出画布范围") + except Exception as e: + print(f" 绘制图像 #{i} 错误: {e}") + import traceback + traceback.print_exc() + else: + # 如果没有图像,至少显示一些提示 + if self.debug_count <= 3: + print(" ⚠️ 没有图像可绘制") + # 在画布中心显示提示 + canvas.create_text( + canvas_width // 2, + canvas_height // 2, + text="等待画面...\n\n如果长时间无画面,请检查:\n1. 采集卡是否正常工作\n2. 配置是否正确", + fill='yellow', + font=('Arial', 14), + justify=tk.CENTER + ) # 再绘制所有文本(上层) for x, y, text, color in texts_to_draw: try: - if color == 'white': - canvas.create_text(x, y, text=text, fill=color, font=('Arial', 10, 'bold')) - else: - canvas.create_text(x, y, text=text, fill=color, font=('Arial', 10)) + if 0 <= x <= canvas_width and 0 <= y <= canvas_height: + if color == 'white': + canvas.create_text(x, y, text=text, fill=color, font=('Arial', 10, 'bold')) + else: + canvas.create_text(x, y, text=text, fill=color, font=('Arial', 10)) except Exception as e: print(f"绘制文本错误: {e}") + # 强制更新画布显示 + canvas.update_idletasks() + # 绘制分割线,区分不同的采集卡窗口 try: # 绘制垂直分割线(列之间的分割线) From 754501b933410b90fa3c21238e709586da1772f1 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Oct 2025 17:50:33 +0800 Subject: [PATCH 2/5] =?UTF-8?q?=E9=87=87=E9=9B=86=E5=8D=A1bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- preview.py | 80 ++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 21 deletions(-) diff --git a/preview.py b/preview.py index ca89278..68482c8 100644 --- a/preview.py +++ b/preview.py @@ -194,8 +194,9 @@ class PreviewWindow: canvas = Canvas(root, bg='black', width=preview_width, height=preview_height) canvas.pack(fill=tk.BOTH, expand=True) - # 存储图像对象 - self.photo_objects = {} + # 存储图像对象(使用列表保存所有PhotoImage引用,防止GC) + self.photo_objects_list = [] + self.photo_objects = {} # 按索引映射 # 用于控制调试输出(只打印前几次) self.debug_count = 0 @@ -219,10 +220,27 @@ class PreviewWindow: root.after(33, update_frames_once) return + # 重新读取配置,确保获取最新值(修复配置读取问题) + config_manager.load_config() + display = config_manager.config.get('display', {}) + current_preview_width = display.get('preview_width', 1000) + current_preview_height = display.get('preview_height', 700) + current_columns = display.get('preview_columns', 2) + current_rows = display.get('preview_rows', 2) + + # 验证配置值是否有效 + if current_preview_width < 100 or current_preview_height < 100: + current_preview_width = 1000 + current_preview_height = 700 + if current_columns < 1 or current_columns > 10: + current_columns = 2 + if current_rows < 1 or current_rows > 10: + current_rows = 2 + # 计算每个预览窗口的位置和大小 - # 直接使用配置值作为画布尺寸(macOS上窗口尺寸可能在显示前返回默认值) - canvas_width = preview_width - canvas_height = preview_height + # 直接使用配置值作为画布尺寸 + canvas_width = current_preview_width + canvas_height = current_preview_height # 尝试获取实际的窗口尺寸,如果有效则使用(大于配置值说明可能被手动调整了) try: @@ -237,8 +255,8 @@ class PreviewWindow: except: pass # 如果获取失败,使用配置值 - cell_width = max(10, canvas_width // columns) - cell_height = max(10, canvas_height // rows) + cell_width = max(10, canvas_width // current_columns) + cell_height = max(10, canvas_height // current_rows) # 先收集所有需要显示的图像 images_to_draw = [] @@ -250,8 +268,8 @@ class PreviewWindow: texts_to_draw.append((canvas_width // 2, canvas_height // 2, "未找到采集卡", 'red')) for idx in self.caps.keys(): - row = frame_idx // columns - col = frame_idx % columns + row = frame_idx // current_columns + col = frame_idx % current_columns x = col * cell_width y = row * cell_height center_x = x + cell_width // 2 @@ -289,7 +307,7 @@ class PreviewWindow: self.debug_count += 1 if self.debug_count <= 3: # 只打印前3次 print(f"🔍 预览调试 #{self.debug_count}:") - print(f" 配置尺寸: {preview_width}x{preview_height}") + print(f" 配置尺寸: {current_preview_width}x{current_preview_height}") print(f" 实际画布: {canvas_width}x{canvas_height}") print(f" 单元格大小: {cell_width}x{cell_height}") print(f" 原始帧: {w}x{h}") @@ -303,8 +321,10 @@ class PreviewWindow: resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) pil_image = Image.fromarray(resized_frame) photo = ImageTk.PhotoImage(image=pil_image) - # 保持引用,避免被GC - self.photo_objects[idx] = photo + + # 多重引用保护,防止被GC回收 + self.photo_objects[idx] = photo # 按索引保存 + self.photo_objects_list.append(photo) # 在列表中保存(防止GC) images_to_draw.append((photo, center_x, center_y)) texts_to_draw.append((center_x, y + 15, name, 'white')) @@ -324,21 +344,26 @@ class PreviewWindow: texts_to_draw.append((center_x, center_y, f"{name}\n等待画面...", 'gray')) frame_idx += 1 - # 清空画布 + # 清空画布(保留photo引用,只清空画布内容) canvas.delete("all") # 先绘制所有图像(底层) if self.debug_count <= 3: print(f"📊 绘制状态: {len(images_to_draw)} 个图像, {len(texts_to_draw)} 个文本, 画布={canvas_width}x{canvas_height}") + print(f" 当前保存的照片对象数量: {len(self.photo_objects_list)}") if images_to_draw: + # 创建一个临时列表保存所有photo引用,防止在绘制时被GC + photos_to_keep = [] for i, (photo, x, y) in enumerate(images_to_draw): try: # 确保坐标在画布范围内 if 0 <= x <= canvas_width and 0 <= y <= canvas_height: + # 在绘制前保存引用 + photos_to_keep.append(photo) canvas.create_image(x, y, image=photo, anchor='center') if self.debug_count <= 3 and i == 0: - print(f" 绘制图像 #{i} 到位置 ({x}, {y})") + print(f" 绘制图像 #{i} 到位置 ({x}, {y}), photo id: {id(photo)}") else: if self.debug_count <= 3: print(f" ⚠️ 图像 #{i} 位置 ({x}, {y}) 超出画布范围") @@ -346,6 +371,13 @@ class PreviewWindow: print(f" 绘制图像 #{i} 错误: {e}") import traceback traceback.print_exc() + + # 确保照片对象不被回收(保存引用到实例变量) + # 只保留最近的一批照片对象,避免内存泄漏 + self.photo_objects_list = photos_to_keep[:] # 复制列表 + # 限制列表大小,只保留最近的20个对象 + if len(self.photo_objects_list) > 20: + self.photo_objects_list = self.photo_objects_list[-20:] else: # 如果没有图像,至少显示一些提示 if self.debug_count <= 3: @@ -377,7 +409,7 @@ class PreviewWindow: # 绘制分割线,区分不同的采集卡窗口 try: # 绘制垂直分割线(列之间的分割线) - for col in range(1, columns): + for col in range(1, current_columns): x = col * cell_width canvas.create_line( x, 0, @@ -388,7 +420,7 @@ class PreviewWindow: ) # 绘制水平分割线(行之间的分割线) - for row in range(1, rows): + for row in range(1, current_rows): y = row * cell_height canvas.create_line( 0, y, @@ -409,14 +441,20 @@ class PreviewWindow: def on_canvas_click(event): """点击画布事件""" - window_width = root.winfo_width() - window_height = root.winfo_height() - cell_width = window_width // columns - cell_height = window_height // rows + # 重新读取配置以获取最新的columns和rows + config_manager.load_config() + display = config_manager.config.get('display', {}) + click_columns = display.get('preview_columns', 2) + click_rows = display.get('preview_rows', 2) + + window_width = root.winfo_width() if root.winfo_width() > 1 else preview_width + window_height = root.winfo_height() if root.winfo_height() > 1 else preview_height + cell_width = window_width // click_columns + cell_height = window_height // click_rows col = int(event.x // cell_width) row = int(event.y // cell_height) - index = row * columns + col + index = row * click_columns + col # 找到对应的配置 if index < len(self.caps): From 94fa69043b441a4c8403f7c73aef068a87974203 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Oct 2025 17:55:54 +0800 Subject: [PATCH 3/5] =?UTF-8?q?=E9=87=87=E9=9B=86=E5=8D=A1bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- preview.py | 64 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/preview.py b/preview.py index 68482c8..179be11 100644 --- a/preview.py +++ b/preview.py @@ -322,11 +322,11 @@ class PreviewWindow: pil_image = Image.fromarray(resized_frame) photo = ImageTk.PhotoImage(image=pil_image) - # 多重引用保护,防止被GC回收 - self.photo_objects[idx] = photo # 按索引保存 - self.photo_objects_list.append(photo) # 在列表中保存(防止GC) + # 保存引用(按索引保存,方便查找) + self.photo_objects[idx] = photo - images_to_draw.append((photo, center_x, center_y)) + # 添加到绘制列表(在列表中保存引用,防止GC) + images_to_draw.append((photo, center_x, center_y, idx)) texts_to_draw.append((center_x, y + 15, name, 'white')) frame_idx += 1 @@ -353,31 +353,57 @@ class PreviewWindow: print(f" 当前保存的照片对象数量: {len(self.photo_objects_list)}") if images_to_draw: - # 创建一个临时列表保存所有photo引用,防止在绘制时被GC - photos_to_keep = [] - for i, (photo, x, y) in enumerate(images_to_draw): + # 先收集所有photo对象到列表中,确保引用不丢失 + photos_current_frame = [] + + for i, item in enumerate(images_to_draw): + if len(item) == 4: + photo, x, y, idx = item + else: + # 兼容旧格式(如果还有的话) + photo, x, y = item[:3] + idx = None + try: # 确保坐标在画布范围内 if 0 <= x <= canvas_width and 0 <= y <= canvas_height: - # 在绘制前保存引用 - photos_to_keep.append(photo) + # 先保存引用到列表(防止GC) + photos_current_frame.append(photo) + + # 然后绘制 canvas.create_image(x, y, image=photo, anchor='center') + if self.debug_count <= 3 and i == 0: - print(f" 绘制图像 #{i} 到位置 ({x}, {y}), photo id: {id(photo)}") + print(f" 绘制图像 #{i} (idx={idx}) 到位置 ({x}, {y})") else: if self.debug_count <= 3: print(f" ⚠️ 图像 #{i} 位置 ({x}, {y}) 超出画布范围") except Exception as e: - print(f" 绘制图像 #{i} 错误: {e}") - import traceback - traceback.print_exc() + error_msg = str(e).lower() + print(f" ❌ 绘制图像 #{i} 时出错: {type(e).__name__}: {e}") + + if "pyimage" in error_msg: + # PhotoImage 对象被 GC 了,尝试恢复 + if self.debug_count <= 5: + print(f" ⚠️ PhotoImage 对象丢失,尝试从字典恢复 (idx={idx})") + if idx is not None and idx in self.photo_objects: + try: + photo = self.photo_objects[idx] + photos_current_frame.append(photo) + canvas.create_image(x, y, image=photo, anchor='center') + if self.debug_count <= 5: + print(f" ✅ 已从字典恢复并重新绘制") + except Exception as e2: + if self.debug_count <= 5: + print(f" ❌ 恢复失败: {e2}") + else: + # 其他类型的错误,打印完整堆栈 + import traceback + traceback.print_exc() - # 确保照片对象不被回收(保存引用到实例变量) - # 只保留最近的一批照片对象,避免内存泄漏 - self.photo_objects_list = photos_to_keep[:] # 复制列表 - # 限制列表大小,只保留最近的20个对象 - if len(self.photo_objects_list) > 20: - self.photo_objects_list = self.photo_objects_list[-20:] + # 保存当前帧的所有photo引用(替换旧的列表,只保留当前帧) + # 这样确保正在显示的photo对象不会被GC + self.photo_objects_list = photos_current_frame[:] # 复制列表 else: # 如果没有图像,至少显示一些提示 if self.debug_count <= 3: From b87a26d3863634cb0a5d7c7a49e631348755c1b3 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Oct 2025 18:11:25 +0800 Subject: [PATCH 4/5] =?UTF-8?q?=E9=87=87=E9=9B=86=E5=8D=A1bug=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- preview.py | 228 ++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 165 insertions(+), 63 deletions(-) diff --git a/preview.py b/preview.py index 179be11..835c5fe 100644 --- a/preview.py +++ b/preview.py @@ -126,8 +126,17 @@ class PreviewWindow: print(f"✅ 成功加载 {loaded_count} 个采集卡") def capture_frames(self): - """捕获帧""" + """每5秒截取一张图""" + import time + first_capture = True # 第一次立即截取 while self.running: + if first_capture: + first_capture = False + # 第一次立即截取,不等待 + pass + else: + # 之后每5秒截取一次 + time.sleep(5.0) for idx, data in self.caps.items(): try: ret, frame = data['cap'].read() @@ -145,19 +154,18 @@ class PreviewWindow: # 转换颜色空间 frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.frames[idx] = frame_rgb + print(f"📸 采集卡 {idx} 截图已更新") else: print(f"⚠️ 采集卡 {idx} 裁剪参数无效") else: # 读取失败,清除旧帧 if idx in self.frames: self.frames[idx] = None + print(f"⚠️ 采集卡 {idx} 读取失败") except Exception as e: print(f"捕获帧 {idx} 错误: {e}") import traceback traceback.print_exc() - - import time - time.sleep(0.01) # 避免CPU占用过高 def create_grid_window(self): """创建网格窗口""" @@ -187,7 +195,7 @@ class PreviewWindow: print(f"📐 预览窗口配置: {preview_width}x{preview_height}, 网格: {columns}x{rows}") root = tk.Tk() - root.title("采集卡预览 - 点击放大") + root.title("采集卡预览(每5秒更新)- 点击放大") root.geometry(f"{preview_width}x{preview_height}") root.update_idletasks() # 立即更新窗口尺寸 @@ -197,6 +205,7 @@ class PreviewWindow: # 存储图像对象(使用列表保存所有PhotoImage引用,防止GC) self.photo_objects_list = [] self.photo_objects = {} # 按索引映射 + self.canvas_image_items = {} # 保存canvas中的图像项ID,用于更新而不是删除重建 # 用于控制调试输出(只打印前几次) self.debug_count = 0 @@ -344,23 +353,31 @@ class PreviewWindow: texts_to_draw.append((center_x, center_y, f"{name}\n等待画面...", 'gray')) frame_idx += 1 - # 清空画布(保留photo引用,只清空画布内容) - canvas.delete("all") + # 先收集所有photo对象到列表中,确保引用不丢失 + photos_current_frame = [] # 先绘制所有图像(底层) if self.debug_count <= 3: print(f"📊 绘制状态: {len(images_to_draw)} 个图像, {len(texts_to_draw)} 个文本, 画布={canvas_width}x{canvas_height}") - print(f" 当前保存的照片对象数量: {len(self.photo_objects_list)}") if images_to_draw: - # 先收集所有photo对象到列表中,确保引用不丢失 - photos_current_frame = [] + # 删除旧的文本和分割线,但保留图像项(这样PhotoImage引用不会被释放) + # 只删除文本项和线条项 + for item_id in list(canvas.find_all()): + item_tags = canvas.gettags(item_id) + item_type = canvas.type(item_id) + # 删除文本和线条,保留图像 + if item_type in ['text', 'line']: + try: + canvas.delete(item_id) + except: + pass + # 现在更新或创建图像项 for i, item in enumerate(images_to_draw): if len(item) == 4: photo, x, y, idx = item else: - # 兼容旧格式(如果还有的话) photo, x, y = item[:3] idx = None @@ -370,45 +387,58 @@ class PreviewWindow: # 先保存引用到列表(防止GC) photos_current_frame.append(photo) - # 然后绘制 - canvas.create_image(x, y, image=photo, anchor='center') - - if self.debug_count <= 3 and i == 0: - print(f" 绘制图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + # 更新或创建图像项 + if idx in self.canvas_image_items: + # 更新现有图像项 + try: + item_id = self.canvas_image_items[idx] + canvas.coords(item_id, x, y) + canvas.itemconfig(item_id, image=photo) + if self.debug_count <= 3 and i == 0: + print(f" 更新图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + except: + # 如果更新失败,删除旧的并创建新的 + try: + canvas.delete(self.canvas_image_items[idx]) + except: + pass + item_id = canvas.create_image(x, y, image=photo, anchor='center') + self.canvas_image_items[idx] = item_id + if self.debug_count <= 3 and i == 0: + print(f" 重新创建图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + else: + # 创建新图像项 + item_id = canvas.create_image(x, y, image=photo, anchor='center') + self.canvas_image_items[idx] = item_id + if self.debug_count <= 3 and i == 0: + print(f" 创建图像 #{i} (idx={idx}) 到位置 ({x}, {y})") else: if self.debug_count <= 3: print(f" ⚠️ 图像 #{i} 位置 ({x}, {y}) 超出画布范围") except Exception as e: error_msg = str(e).lower() print(f" ❌ 绘制图像 #{i} 时出错: {type(e).__name__}: {e}") - - if "pyimage" in error_msg: - # PhotoImage 对象被 GC 了,尝试恢复 - if self.debug_count <= 5: - print(f" ⚠️ PhotoImage 对象丢失,尝试从字典恢复 (idx={idx})") - if idx is not None and idx in self.photo_objects: - try: - photo = self.photo_objects[idx] - photos_current_frame.append(photo) - canvas.create_image(x, y, image=photo, anchor='center') - if self.debug_count <= 5: - print(f" ✅ 已从字典恢复并重新绘制") - except Exception as e2: - if self.debug_count <= 5: - print(f" ❌ 恢复失败: {e2}") - else: - # 其他类型的错误,打印完整堆栈 - import traceback - traceback.print_exc() + import traceback + traceback.print_exc() - # 保存当前帧的所有photo引用(替换旧的列表,只保留当前帧) - # 这样确保正在显示的photo对象不会被GC - self.photo_objects_list = photos_current_frame[:] # 复制列表 + # 删除不再存在的图像项 + current_indices = set(idx for item in images_to_draw if len(item) >= 4 for idx in [item[3]]) + for idx in list(self.canvas_image_items.keys()): + if idx not in current_indices: + try: + canvas.delete(self.canvas_image_items[idx]) + del self.canvas_image_items[idx] + except: + pass + + # 保存当前帧的所有photo引用 + self.photo_objects_list = photos_current_frame[:] else: - # 如果没有图像,至少显示一些提示 + # 如果没有图像,清空所有并显示提示 + canvas.delete("all") + self.canvas_image_items.clear() if self.debug_count <= 3: print(" ⚠️ 没有图像可绘制") - # 在画布中心显示提示 canvas.create_text( canvas_width // 2, canvas_height // 2, @@ -429,6 +459,20 @@ class PreviewWindow: except Exception as e: print(f"绘制文本错误: {e}") + # 绘制更新时间提示(右上角) + try: + import datetime + update_time = datetime.datetime.now().strftime("%H:%M:%S") + canvas.create_text( + canvas_width - 10, 15, + text=f"最后更新: {update_time}", + fill='gray', + font=('Arial', 8), + anchor='ne' + ) + except: + pass + # 强制更新画布显示 canvas.update_idletasks() @@ -462,8 +506,8 @@ class PreviewWindow: print(f"更新帧错误: {e}") import traceback traceback.print_exc() - # 约30fps - root.after(33, update_frames_once) + # 每1秒检查一次是否有新截图(截图在另一个线程每5秒更新) + root.after(1000, update_frames_once) def on_canvas_click(event): """点击画布事件""" @@ -516,52 +560,109 @@ class PreviewWindow: root.mainloop() def show_large_window(self, idx): - """显示大窗口""" + """显示大窗口(实时显示指定采集卡)""" if self.large_window is not None and self.large_window.winfo_exists(): self.large_window.destroy() self.large_window = tk.Toplevel() - self.large_window.title(f"放大视图 - {self.caps[idx]['name']}") + self.large_window.title(f"放大视图 - {self.caps[idx]['name']} (实时)") self.large_window.geometry("1280x720") canvas = Canvas(self.large_window, bg='black') canvas.pack(fill=tk.BOTH, expand=True) photo_obj = {} + canvas_image_item = None # 保存canvas中的图像项ID def update_large_once(): if not self.running or not self.large_window.winfo_exists(): return try: + # 从采集卡实时读取帧(不依赖截图) + if idx not in self.caps: + canvas.delete("all") + canvas.create_text( + 640, 360, + text="采集卡已断开", + fill='red', + font=('Arial', 16) + ) + self.large_window.after(1000, update_large_once) + return + + cap = self.caps[idx]['cap'] + ret, frame = cap.read() + # 获取窗口大小 window_width = self.large_window.winfo_width() if self.large_window.winfo_width() > 1 else 1280 window_height = self.large_window.winfo_height() if self.large_window.winfo_height() > 1 else 720 - if idx in self.frames and self.frames[idx] is not None: - # 先处理图像,再清空画布 - frame = self.frames[idx] - h, w = frame.shape[:2] + if ret and frame is not None: + # 裁剪到配置的区域 + height, width = frame.shape[:2] + crop_top = 30 + crop_bottom = min(crop_top + 720, height) + crop_width = min(1280, width) + + # 确保裁剪范围有效 + if crop_bottom > crop_top and crop_width > 0: + frame = frame[crop_top:crop_bottom, 0:crop_width] + + # 转换颜色空间 + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + h, w = frame_rgb.shape[:2] - # 调整到窗口大小 - scale = min(window_width / w, window_height / h) - new_w = int(w * scale) - new_h = int(h * scale) + # 调整到窗口大小 + scale = min(window_width / w, window_height / h) + new_w = int(w * scale) + new_h = int(h * scale) - resized_frame = cv2.resize(frame, (new_w, new_h)) - # 确保颜色通道正确(BGR -> RGB) - if len(resized_frame.shape) == 3 and resized_frame.shape[2] == 3: - resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) - pil_image = Image.fromarray(resized_frame) - photo = ImageTk.PhotoImage(image=pil_image) - # 保存引用到字典,确保不被GC - photo_obj['img'] = photo + resized_frame = cv2.resize(frame_rgb, (new_w, new_h)) + pil_image = Image.fromarray(resized_frame) + photo = ImageTk.PhotoImage(image=pil_image) + # 保存引用到字典,确保不被GC + photo_obj['img'] = photo - # 清空并绘制新图像 - canvas.delete("all") - canvas.create_image(window_width // 2, window_height // 2, image=photo, anchor='center') + # 更新或创建图像项 + if canvas_image_item is not None: + try: + # 更新现有图像项 + canvas.coords(canvas_image_item, window_width // 2, window_height // 2) + canvas.itemconfig(canvas_image_item, image=photo) + except: + # 如果更新失败,删除旧的并创建新的 + try: + canvas.delete(canvas_image_item) + except: + pass + canvas_image_item = canvas.create_image( + window_width // 2, + window_height // 2, + image=photo, + anchor='center' + ) + else: + # 创建新图像项 + canvas.delete("all") # 首次创建时清空 + canvas_image_item = canvas.create_image( + window_width // 2, + window_height // 2, + image=photo, + anchor='center' + ) + else: + canvas.delete("all") + canvas.create_text( + window_width // 2, + window_height // 2, + text="裁剪参数无效", + fill='red', + font=('Arial', 16) + ) else: # 显示等待提示 canvas.delete("all") + canvas_image_item = None canvas.create_text( window_width // 2, window_height // 2, @@ -572,6 +673,7 @@ class PreviewWindow: except Exception as e: if "pyimage" not in str(e).lower(): # 忽略pyimage错误,避免刷屏 print(f"更新大窗口错误: {e}") + # 约30fps,实时显示 self.large_window.after(33, update_large_once) self.large_window.after(33, update_large_once) From 2399f87d57981bfc3155f4710e7d2ae7becd8071 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Oct 2025 18:15:12 +0800 Subject: [PATCH 5/5] =?UTF-8?q?=E5=9B=BE=E7=89=87=E5=89=8D=E7=9A=84?= =?UTF-8?q?=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/huojv.iml | 2 +- .idea/misc.xml | 2 +- preview.py | 228 +++++++++++++++++++++++++++++++++++------------- 3 files changed, 167 insertions(+), 65 deletions(-) diff --git a/.idea/huojv.iml b/.idea/huojv.iml index 8b74e97..8388dbc 100644 --- a/.idea/huojv.iml +++ b/.idea/huojv.iml @@ -2,7 +2,7 @@ - + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index b02dc17..5f01a00 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -3,5 +3,5 @@ - + \ No newline at end of file diff --git a/preview.py b/preview.py index 179be11..835c5fe 100644 --- a/preview.py +++ b/preview.py @@ -126,8 +126,17 @@ class PreviewWindow: print(f"✅ 成功加载 {loaded_count} 个采集卡") def capture_frames(self): - """捕获帧""" + """每5秒截取一张图""" + import time + first_capture = True # 第一次立即截取 while self.running: + if first_capture: + first_capture = False + # 第一次立即截取,不等待 + pass + else: + # 之后每5秒截取一次 + time.sleep(5.0) for idx, data in self.caps.items(): try: ret, frame = data['cap'].read() @@ -145,19 +154,18 @@ class PreviewWindow: # 转换颜色空间 frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self.frames[idx] = frame_rgb + print(f"📸 采集卡 {idx} 截图已更新") else: print(f"⚠️ 采集卡 {idx} 裁剪参数无效") else: # 读取失败,清除旧帧 if idx in self.frames: self.frames[idx] = None + print(f"⚠️ 采集卡 {idx} 读取失败") except Exception as e: print(f"捕获帧 {idx} 错误: {e}") import traceback traceback.print_exc() - - import time - time.sleep(0.01) # 避免CPU占用过高 def create_grid_window(self): """创建网格窗口""" @@ -187,7 +195,7 @@ class PreviewWindow: print(f"📐 预览窗口配置: {preview_width}x{preview_height}, 网格: {columns}x{rows}") root = tk.Tk() - root.title("采集卡预览 - 点击放大") + root.title("采集卡预览(每5秒更新)- 点击放大") root.geometry(f"{preview_width}x{preview_height}") root.update_idletasks() # 立即更新窗口尺寸 @@ -197,6 +205,7 @@ class PreviewWindow: # 存储图像对象(使用列表保存所有PhotoImage引用,防止GC) self.photo_objects_list = [] self.photo_objects = {} # 按索引映射 + self.canvas_image_items = {} # 保存canvas中的图像项ID,用于更新而不是删除重建 # 用于控制调试输出(只打印前几次) self.debug_count = 0 @@ -344,23 +353,31 @@ class PreviewWindow: texts_to_draw.append((center_x, center_y, f"{name}\n等待画面...", 'gray')) frame_idx += 1 - # 清空画布(保留photo引用,只清空画布内容) - canvas.delete("all") + # 先收集所有photo对象到列表中,确保引用不丢失 + photos_current_frame = [] # 先绘制所有图像(底层) if self.debug_count <= 3: print(f"📊 绘制状态: {len(images_to_draw)} 个图像, {len(texts_to_draw)} 个文本, 画布={canvas_width}x{canvas_height}") - print(f" 当前保存的照片对象数量: {len(self.photo_objects_list)}") if images_to_draw: - # 先收集所有photo对象到列表中,确保引用不丢失 - photos_current_frame = [] + # 删除旧的文本和分割线,但保留图像项(这样PhotoImage引用不会被释放) + # 只删除文本项和线条项 + for item_id in list(canvas.find_all()): + item_tags = canvas.gettags(item_id) + item_type = canvas.type(item_id) + # 删除文本和线条,保留图像 + if item_type in ['text', 'line']: + try: + canvas.delete(item_id) + except: + pass + # 现在更新或创建图像项 for i, item in enumerate(images_to_draw): if len(item) == 4: photo, x, y, idx = item else: - # 兼容旧格式(如果还有的话) photo, x, y = item[:3] idx = None @@ -370,45 +387,58 @@ class PreviewWindow: # 先保存引用到列表(防止GC) photos_current_frame.append(photo) - # 然后绘制 - canvas.create_image(x, y, image=photo, anchor='center') - - if self.debug_count <= 3 and i == 0: - print(f" 绘制图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + # 更新或创建图像项 + if idx in self.canvas_image_items: + # 更新现有图像项 + try: + item_id = self.canvas_image_items[idx] + canvas.coords(item_id, x, y) + canvas.itemconfig(item_id, image=photo) + if self.debug_count <= 3 and i == 0: + print(f" 更新图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + except: + # 如果更新失败,删除旧的并创建新的 + try: + canvas.delete(self.canvas_image_items[idx]) + except: + pass + item_id = canvas.create_image(x, y, image=photo, anchor='center') + self.canvas_image_items[idx] = item_id + if self.debug_count <= 3 and i == 0: + print(f" 重新创建图像 #{i} (idx={idx}) 到位置 ({x}, {y})") + else: + # 创建新图像项 + item_id = canvas.create_image(x, y, image=photo, anchor='center') + self.canvas_image_items[idx] = item_id + if self.debug_count <= 3 and i == 0: + print(f" 创建图像 #{i} (idx={idx}) 到位置 ({x}, {y})") else: if self.debug_count <= 3: print(f" ⚠️ 图像 #{i} 位置 ({x}, {y}) 超出画布范围") except Exception as e: error_msg = str(e).lower() print(f" ❌ 绘制图像 #{i} 时出错: {type(e).__name__}: {e}") - - if "pyimage" in error_msg: - # PhotoImage 对象被 GC 了,尝试恢复 - if self.debug_count <= 5: - print(f" ⚠️ PhotoImage 对象丢失,尝试从字典恢复 (idx={idx})") - if idx is not None and idx in self.photo_objects: - try: - photo = self.photo_objects[idx] - photos_current_frame.append(photo) - canvas.create_image(x, y, image=photo, anchor='center') - if self.debug_count <= 5: - print(f" ✅ 已从字典恢复并重新绘制") - except Exception as e2: - if self.debug_count <= 5: - print(f" ❌ 恢复失败: {e2}") - else: - # 其他类型的错误,打印完整堆栈 - import traceback - traceback.print_exc() + import traceback + traceback.print_exc() - # 保存当前帧的所有photo引用(替换旧的列表,只保留当前帧) - # 这样确保正在显示的photo对象不会被GC - self.photo_objects_list = photos_current_frame[:] # 复制列表 + # 删除不再存在的图像项 + current_indices = set(idx for item in images_to_draw if len(item) >= 4 for idx in [item[3]]) + for idx in list(self.canvas_image_items.keys()): + if idx not in current_indices: + try: + canvas.delete(self.canvas_image_items[idx]) + del self.canvas_image_items[idx] + except: + pass + + # 保存当前帧的所有photo引用 + self.photo_objects_list = photos_current_frame[:] else: - # 如果没有图像,至少显示一些提示 + # 如果没有图像,清空所有并显示提示 + canvas.delete("all") + self.canvas_image_items.clear() if self.debug_count <= 3: print(" ⚠️ 没有图像可绘制") - # 在画布中心显示提示 canvas.create_text( canvas_width // 2, canvas_height // 2, @@ -429,6 +459,20 @@ class PreviewWindow: except Exception as e: print(f"绘制文本错误: {e}") + # 绘制更新时间提示(右上角) + try: + import datetime + update_time = datetime.datetime.now().strftime("%H:%M:%S") + canvas.create_text( + canvas_width - 10, 15, + text=f"最后更新: {update_time}", + fill='gray', + font=('Arial', 8), + anchor='ne' + ) + except: + pass + # 强制更新画布显示 canvas.update_idletasks() @@ -462,8 +506,8 @@ class PreviewWindow: print(f"更新帧错误: {e}") import traceback traceback.print_exc() - # 约30fps - root.after(33, update_frames_once) + # 每1秒检查一次是否有新截图(截图在另一个线程每5秒更新) + root.after(1000, update_frames_once) def on_canvas_click(event): """点击画布事件""" @@ -516,52 +560,109 @@ class PreviewWindow: root.mainloop() def show_large_window(self, idx): - """显示大窗口""" + """显示大窗口(实时显示指定采集卡)""" if self.large_window is not None and self.large_window.winfo_exists(): self.large_window.destroy() self.large_window = tk.Toplevel() - self.large_window.title(f"放大视图 - {self.caps[idx]['name']}") + self.large_window.title(f"放大视图 - {self.caps[idx]['name']} (实时)") self.large_window.geometry("1280x720") canvas = Canvas(self.large_window, bg='black') canvas.pack(fill=tk.BOTH, expand=True) photo_obj = {} + canvas_image_item = None # 保存canvas中的图像项ID def update_large_once(): if not self.running or not self.large_window.winfo_exists(): return try: + # 从采集卡实时读取帧(不依赖截图) + if idx not in self.caps: + canvas.delete("all") + canvas.create_text( + 640, 360, + text="采集卡已断开", + fill='red', + font=('Arial', 16) + ) + self.large_window.after(1000, update_large_once) + return + + cap = self.caps[idx]['cap'] + ret, frame = cap.read() + # 获取窗口大小 window_width = self.large_window.winfo_width() if self.large_window.winfo_width() > 1 else 1280 window_height = self.large_window.winfo_height() if self.large_window.winfo_height() > 1 else 720 - if idx in self.frames and self.frames[idx] is not None: - # 先处理图像,再清空画布 - frame = self.frames[idx] - h, w = frame.shape[:2] + if ret and frame is not None: + # 裁剪到配置的区域 + height, width = frame.shape[:2] + crop_top = 30 + crop_bottom = min(crop_top + 720, height) + crop_width = min(1280, width) + + # 确保裁剪范围有效 + if crop_bottom > crop_top and crop_width > 0: + frame = frame[crop_top:crop_bottom, 0:crop_width] + + # 转换颜色空间 + frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) + h, w = frame_rgb.shape[:2] - # 调整到窗口大小 - scale = min(window_width / w, window_height / h) - new_w = int(w * scale) - new_h = int(h * scale) + # 调整到窗口大小 + scale = min(window_width / w, window_height / h) + new_w = int(w * scale) + new_h = int(h * scale) - resized_frame = cv2.resize(frame, (new_w, new_h)) - # 确保颜色通道正确(BGR -> RGB) - if len(resized_frame.shape) == 3 and resized_frame.shape[2] == 3: - resized_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB) - pil_image = Image.fromarray(resized_frame) - photo = ImageTk.PhotoImage(image=pil_image) - # 保存引用到字典,确保不被GC - photo_obj['img'] = photo + resized_frame = cv2.resize(frame_rgb, (new_w, new_h)) + pil_image = Image.fromarray(resized_frame) + photo = ImageTk.PhotoImage(image=pil_image) + # 保存引用到字典,确保不被GC + photo_obj['img'] = photo - # 清空并绘制新图像 - canvas.delete("all") - canvas.create_image(window_width // 2, window_height // 2, image=photo, anchor='center') + # 更新或创建图像项 + if canvas_image_item is not None: + try: + # 更新现有图像项 + canvas.coords(canvas_image_item, window_width // 2, window_height // 2) + canvas.itemconfig(canvas_image_item, image=photo) + except: + # 如果更新失败,删除旧的并创建新的 + try: + canvas.delete(canvas_image_item) + except: + pass + canvas_image_item = canvas.create_image( + window_width // 2, + window_height // 2, + image=photo, + anchor='center' + ) + else: + # 创建新图像项 + canvas.delete("all") # 首次创建时清空 + canvas_image_item = canvas.create_image( + window_width // 2, + window_height // 2, + image=photo, + anchor='center' + ) + else: + canvas.delete("all") + canvas.create_text( + window_width // 2, + window_height // 2, + text="裁剪参数无效", + fill='red', + font=('Arial', 16) + ) else: # 显示等待提示 canvas.delete("all") + canvas_image_item = None canvas.create_text( window_width // 2, window_height // 2, @@ -572,6 +673,7 @@ class PreviewWindow: except Exception as e: if "pyimage" not in str(e).lower(): # 忽略pyimage错误,避免刷屏 print(f"更新大窗口错误: {e}") + # 约30fps,实时显示 self.large_window.after(33, update_large_once) self.large_window.after(33, update_large_once)