1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
| import sys import os import time from PyQt6.QtWidgets import ( QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QFileDialog, QComboBox, QMessageBox, QListWidget, QProgressDialog, QProgressBar, QFrame ) from PyQt6.QtGui import QPixmap, QImage from PyQt6.QtCore import Qt, QThread, pyqtSignal import cv2 from detector import YOLODetector import json import shutil
class CameraCapture: def __init__(self, camera_id=0, width=640, height=480): self.camera_id = camera_id self.width = width self.height = height self.cap = None
def open(self): self.cap = cv2.VideoCapture(self.camera_id, cv2.CAP_DSHOW) if self.cap.isOpened(): self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width) self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height) return self.cap.isOpened()
def is_opened(self): return self.cap is not None and self.cap.isOpened()
def read(self): if self.cap and self.cap.isOpened(): return self.cap.read() return False, None
def release(self): if self.cap: self.cap.release() self.cap = None
class CameraProcessorThread(QThread): update_frame = pyqtSignal(QPixmap, dict)
def __init__(self, detector): super().__init__() self.detector = detector self.running = True self.camera = CameraCapture()
def run(self): if not self.camera.open(): return while self.running and self.camera.is_opened(): ret, frame = self.camera.read() if not ret: break
boxes, self.stats = self.detector.detect(frame) self.detector._draw_boxes(frame, boxes)
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgb.shape qimg = QImage(rgb.data, w, h, ch * w, QImage.Format.Format_RGB888) pixmap = QPixmap.fromImage(qimg) self.update_frame.emit(pixmap, self.stats) self.msleep(10)
self.camera.release()
def stop(self): self.running = False self.wait()
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("电子设备检测系统") self.setGeometry(100, 100, 1200, 650)
self.detector = YOLODetector("models/best.pt") self.current_file = None self.processor = None self.progress_dialog = None self.selected_files = [] self.custom_save_path = None self.video_cache = {} self.is_processing = False self.cache_dir_delete = None
main_widget = QWidget() self.layout = QVBoxLayout()
ctrl_layout = QHBoxLayout() self.btn_upload = QPushButton("上传文件") self.btn_upload.clicked.connect(self.upload_file) self.btn_camera = QPushButton("打开摄像头") self.btn_camera.clicked.connect(self.toggle_camera) self.class_select = QComboBox() self.class_select.addItems(["all"] + list(self.detector.class_names.values())) self.class_select.currentTextChanged.connect(self.update_class_filter) self.btn_export = QPushButton("导出结果") self.btn_export.clicked.connect(self.export_results) self.btn_select_export_path = QPushButton("选择导出路径") self.btn_select_export_path.clicked.connect(self.select_export_path)
ctrl_layout.addWidget(self.btn_upload) ctrl_layout.addWidget(self.btn_camera) ctrl_layout.addWidget(self.class_select) ctrl_layout.addWidget(self.btn_export) ctrl_layout.addWidget(self.btn_select_export_path)
self.file_list = QListWidget() self.file_list.itemDoubleClicked.connect(self.on_file_double_clicked)
self.original_image_label = QLabel("原始图像/视频") self.original_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.original_image_label.setMinimumSize(600, 480)
self.annotated_image_label = QLabel("标注后的图像/视频/摄像头") self.annotated_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter) self.annotated_image_label.setMinimumSize(600, 480)
self.splitter = QFrame() self.splitter.setObjectName("splitter") self.splitter.setFrameShape(QFrame.Shape.VLine) self.splitter.setFrameShadow(QFrame.Shadow.Sunken) self.splitter.setStyleSheet("background-color: #F5F5F5; border: 1px dashed #333333;")
display_layout = QHBoxLayout() display_layout.addWidget(self.original_image_label) display_layout.addWidget(self.splitter) display_layout.addWidget(self.annotated_image_label)
self.progress_bar = QProgressBar() self.progress_bar.setRange(0, 100) self.progress_bar.hide()
self.statistics_label = QLabel("目标统计:")
self.layout.addLayout(ctrl_layout) self.layout.addWidget(self.file_list) self.layout.addLayout(display_layout) self.layout.addWidget(self.progress_bar) self.layout.addWidget(self.statistics_label) main_widget.setLayout(self.layout) self.setCentralWidget(main_widget)
self.camera_thread = CameraProcessorThread(self.detector) self.camera_thread.update_frame.connect(self.update_camera_ui)
self.load_styles()
def load_styles(self): current_dir = os.path.dirname(os.path.abspath(__file__)) style_file_path = os.path.join(current_dir, "style.qss")
if not os.path.exists(style_file_path): print("样式表文件不存在") return
with open(style_file_path, "r", encoding="utf-8") as f: style_sheet = f.read()
self.setStyleSheet(style_sheet) print("样式表加载成功")
def upload_file(self): files, _ = QFileDialog.getOpenFileNames( self, "选择文件", "", "媒体文件 (*.jpg *.png *.mp4)" ) if not files: return
for path in files: if path not in self.selected_files: self.selected_files.append(path) self.file_list.addItem(os.path.basename(path))
def on_file_double_clicked(self, item): self.stop_video_threads() self.image_label_clear() self.current_file = None if self.camera_thread.isRunning(): self.camera_thread.stop() self.camera_thread.wait() self.btn_camera.setText("打开摄像头") QMessageBox.information(self, "关闭摄像头","摄像头已关闭") file_name = item.text() self.selected_class = self.class_select.currentText() for path in self.selected_files: if os.path.basename(path) == file_name: self.current_file = path if path.lower().endswith('.mp4'): self.progress_bar.show() else: self.progress_bar.hide() self.process_file(path) break
def update_class_filter(self, selected_class): self.detector.set_class_filter(selected_class)
def process_file(self, path): if path.lower().endswith((".jpg", ".png")): frame, stats = self.detector.process_image(path) if frame is None: QMessageBox.warning(self, "错误", "无法加载检测图像,请检查文件路径或文件完整性") return
original_frame = cv2.imread(path) if original_frame is None: QMessageBox.warning(self, "错误", "无法加载原始图像,请检查文件路径或文件完整性") return
self._display_frame(self.original_image_label, original_frame) self._display_frame(self.annotated_image_label, frame)
self.update_statistics(stats)
elif path.lower().endswith((".mp4")): self.process_video(path)
def _display_frame(self, label, frame): if frame is None: return
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgb.shape qimg = QImage(rgb.data, w, h, ch * w, QImage.Format.Format_RGB888) pixmap = QPixmap.fromImage(qimg) label.setPixmap(pixmap.scaled(600, 480, Qt.AspectRatioMode.KeepAspectRatio))
def process_video(self, path): if self.is_processing: return
"""防止过多次连击文件造成缓存视频时进度条错误 if self.processor and self.processor.isRunning(): self.processor.stop() self.processor.wait() self.processor = None if self.progress_dialog and self.progress_dialog.isVisible(): self.progress_dialog.close() """
self.image_label_clear() self.current_file = path self.progress_bar.hide() self.selected_class = self.class_select.currentText()
if isinstance(path, int): cache_dir = os.path.join(os.getcwd(), ".cache") print(f"缓存目录为{cache_dir}") if not os.path.exists(cache_dir): os.makedirs(cache_dir) cache_file = os.path.join(cache_dir, f"camera_{int(time.time())}.avi") else: cache_dir = os.path.join(os.path.dirname(path), ".cache") print(f"缓存目录为{cache_dir}") if not os.path.exists(cache_dir): os.makedirs(cache_dir) self.cache_dir_delete = cache_dir cache_file = os.path.join(cache_dir, f"processed_{self.selected_class}_{os.path.basename(path)}") stats_path = os.path.join(cache_dir, f"processed_{self.selected_class}_{os.path.splitext(os.path.basename(self.current_file))[0]}.json")
if os.path.exists(cache_file) and not isinstance(path, int) and os.path.exists(stats_path): self.video_cache[path] = cache_file self.play_video(path, cache_file) else: self.is_processing = True print(f"Processing video: {path}") self.file_list.setEnabled(False)
if self.progress_dialog and self.progress_dialog.isVisible(): self.progress_dialog.close() self.progress_dialog = QProgressDialog("视频处理中...", "取消", 0, 100, self) self.progress_dialog.setWindowTitle("缓存视频处理进度") self.progress_dialog.setWindowModality(Qt.WindowModality.ApplicationModal) self.progress_dialog.setAutoClose(True) self.progress_dialog.setCancelButton(None)
self.processor = VideoProcessorThread(self.detector, path, cache_file) if not self.current_file: print(f"current_file is {self.current_file}") exit(1) self.processor.progress.connect(self.update_progress) self.processor.finished.connect(lambda: self.on_processing_finished(path, cache_file)) self.progress_dialog.show()
self.processor.start()
def update_progress(self, processed_frames):
if not self.current_file: return
if self.progress_dialog: cap = cv2.VideoCapture(self.current_file) if not cap.isOpened(): return total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) cap.release()
progress = (processed_frames / total_frames) * 100
if self.progress_dialog: self.progress_dialog.setValue(int(progress)) else: self.processor.stop() QMessageBox.warning(self, "视频处理失败", "无法显示进度对话框")
def on_processing_finished(self, path, cache_file): if self.progress_dialog: self.progress_dialog.setValue(100) self.progress_dialog.close() self.progress_dialog = None
self.video_cache[path] = cache_file
self.is_processing = False self.file_list.setEnabled(True) self.play_video(path, cache_file)
def play_video(self, original_path, processed_path=None): self.stop_video_threads() self.current_file = original_path self.progress_bar.show()
if isinstance(original_path, str) and original_path.lower().endswith('.mp4'): self.progress_bar.show() else: self.progress_bar.hide()
self.original_video_thread = VideoThread(None, original_path, is_original=True) self.original_video_thread.update_frame.connect(self.update_original_ui) if isinstance(original_path, str): self.original_video_thread.progress_updated.connect(self.progress_bar.setValue) self.original_video_thread.frame_index_updated.connect(self.update_statistics_from_cache) self.original_video_thread.start()
if processed_path: self.annotated_video_thread = VideoThread(None, processed_path) self.annotated_video_thread.update_frame.connect(self.update_annotated_ui) self.annotated_video_thread.frame_index_updated.connect(self.update_statistics_from_cache) self.annotated_video_thread.start()
def update_original_ui(self, pixmap, stats): self.original_image_label.setPixmap( pixmap.scaled(600, 480, Qt.AspectRatioMode.KeepAspectRatio) )
def update_annotated_ui(self, pixmap, stats): self.annotated_image_label.setPixmap( pixmap.scaled(600, 480, Qt.AspectRatioMode.KeepAspectRatio) )
self.update_statistics(stats)
def toggle_camera(self): self.stop_video_threads()
if not self.camera_thread.isRunning(): self.camera_thread = CameraProcessorThread(self.detector) self.camera_thread.update_frame.connect(self.update_camera_ui) self.camera_thread.start() self.btn_camera.setText("关闭摄像头") self.image_label_clear() self.progress_bar.hide()
else: self.camera_thread.stop() self.camera_thread.wait() self.btn_camera.setText("打开摄像头") QMessageBox.information(self, "关闭摄像头","摄像头已关闭") self.image_label_clear()
def update_camera_ui(self, pixmap, stats): self.annotated_image_label.setPixmap( pixmap.scaled(600, 480, Qt.AspectRatioMode.KeepAspectRatio) )
self.update_statistics(stats)
def stop_video_threads(self): if hasattr(self, 'original_video_thread') and self.original_video_thread.isRunning(): self.original_video_thread.stop() self.original_video_thread.wait() self.image_label_clear()
if hasattr(self, 'annotated_video_thread') and self.annotated_video_thread.isRunning(): self.annotated_video_thread.stop() self.annotated_video_thread.wait() self.image_label_clear() QMessageBox.information(self,'视频播放停止',"视频手动停止播放")
def export_results(self): if self.current_file is None: QMessageBox.warning(self, "导出失败", "没有文件正在显示") return
if self.custom_save_path is None: self.select_export_path()
selected_class_new = self.class_select.currentText()
if selected_class_new != self.selected_class: QMessageBox.warning(self, "导出失败", "类别选择已更新,将重新处理播放文件") self.process_file(self.current_file) return else: file_extension = os.path.splitext(self.current_file)[1].lower() if file_extension in (".jpg", ".png"):
self.process_file(self.current_file) self.export_image(self.current_file) elif file_extension == ".mp4": self.process_video(self.current_file) self.export_video(self.current_file) else: QMessageBox.warning(self, "导出失败", "不支持的文件类型")
QMessageBox.information(self, "导出完成", f"检测结果已导出到:\n{self.custom_save_path}")
def export_image(self, img_path): file_name = os.path.basename(img_path) output_path = os.path.join(self.custom_save_path, f"result_{self.selected_class}_{file_name}")
frame, _ = self.detector.process_image(img_path) if frame is not None: cv2.imwrite(output_path, frame)
def export_video(self, video_path): if hasattr(self, 'annotated_video_thread') and self.annotated_video_thread.isRunning(): self.stop_video_threads() self.image_label_clear()
if video_path in self.video_cache: processed_path = self.video_cache[video_path] else: QMessageBox.warning(self, "导出失败", "无法找到视频缓存") return
file_name = os.path.basename(video_path) output_path = os.path.join(self.custom_save_path, f"result_{self.selected_class}_{file_name}") os.replace(processed_path, output_path)
def select_export_path(self): selected_path = QFileDialog.getExistingDirectory(self, "选择导出路径") if selected_path: self.custom_save_path = selected_path QMessageBox.information(self, "导出路径", f"导出路径已设置为:\n{self.custom_save_path}") elif self.custom_save_path : QMessageBox.information(self, "导出路径", f"未设置新的导出路径,\n导出路径保持为:\n{self.custom_save_path}") else: QMessageBox.information(self, "导出路径取消", "取消选择导出路径,已重置为 None") self.select_export_path()
def update_statistics(self, stats): if not stats: self.statistics_label.setText("无目标检测结果") return total = sum(stats.values())
stats_str = f"目标总数:{total}\t" for label, count in stats.items(): stats_str += f"{label}: {count}\t" self.statistics_label.setText(stats_str)
def update_statistics_from_cache(self, frame_index):
if not self.current_file: return if isinstance(self.current_file, str) and self.current_file.lower().endswith('.mp4'): video_path = self.current_file cache_dir = os.path.join(os.path.dirname(video_path), ".cache") stats_path = os.path.join(cache_dir, f"processed_{self.selected_class}_{os.path.splitext(os.path.basename(video_path))[0]}.json")
if os.path.exists(stats_path):
with open(stats_path, "r") as f: stats_data = json.load(f)
if "frames" in stats_data and frame_index < len(stats_data["frames"]): stats = stats_data["frames"][frame_index] self.update_statistics(stats) return
else: self.stop_video_threads() self.image_label_clear() self.current_file = video_path self.process_video(self.current_file) self.statistics_label.setText("视频缓存json文件读取失败,无目标检测结果")
def closeEvent(self, event): self.stop_video_threads() self.image_label_clear() if self.cache_dir_delete and os.path.exists(self.cache_dir_delete): print(f"缓存目录存在,位置为{self.cache_dir_delete}") shutil.rmtree(self.cache_dir_delete) print("已删除缓存目录") else: print("未设置缓存目录或缓存目录不存在") event.accept() print("窗口正常关闭")
def image_label_clear(self): self.stop_video_threads() self.original_image_label.clear() self.annotated_image_label.clear() self.original_image_label.setText("原始图像/视频") self.annotated_image_label.setText("标注后的图像/视频/摄像头") self.statistics_label.setText("无目标检测结果") self.progress_bar.hide() self.current_file = None
class VideoProcessorThread(QThread): progress = pyqtSignal(int)
def __init__(self, detector, video_path, output_path): super().__init__() self.detector = detector self.video_path = video_path self.output_path = output_path self.running = True self.stats_cache = [] self.stats_path = os.path.splitext(output_path)[0] + ".json" self.camera = None
def run(self): if isinstance(self.video_path, int): self.camera = CameraCapture(self.video_path) if not self.camera.open(): return cap = self.camera.cap fps = 30 else: cap = cv2.VideoCapture(self.video_path)
if not cap.isOpened(): QMessageBox.warning(self, "错误", "无法处理视频") self.stop() return
fps = cap.get(cv2.CAP_PROP_FPS) if not isinstance(self.video_path, int) else 30 width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*"mp4v") out = cv2.VideoWriter(self.output_path, fourcc, fps, (width, height))
processed_frames = 0
while self.running and cap.isOpened(): ret, frame = cap.read() if not ret: break
boxes, stats = self.detector.detect(frame) self.detector._draw_boxes(frame, boxes)
out.write(frame) self.stats_cache.append(stats) processed_frames += 1 self.progress.emit(processed_frames) self.msleep(10)
if isinstance(self.video_path, int): self.camera.release() else: cap.release() out.release()
print(f"Saving stats to: {self.stats_path}") with open(self.stats_path, "w") as f: json.dump({"frames": self.stats_cache}, f)
def stop(self): self.running = False self.wait() if os.path.exists(self.output_path): os.remove(self.output_path) os.remove(self.stats_path) self.video_path = None
class VideoThread(QThread): update_frame = pyqtSignal(QPixmap, dict) progress_updated = pyqtSignal(int) frame_index_updated = pyqtSignal(int)
def __init__(self, detector, source, is_original=False): super().__init__() self.detector = detector self.source = source self.is_original = is_original self.running = True self.frame_index = 0 self.camera = None
def run(self): if isinstance(self.source, int): self.camera = CameraCapture(self.source) if not self.camera.open(): return cap = self.camera.cap total_frames = 0 else: cap = cv2.VideoCapture(self.source) total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
while self.running and cap.isOpened(): if isinstance(self.source, int): ret, frame = self.camera.read() else: ret, frame = cap.read()
if not ret: break
if total_frames > 0: current_pos = cap.get(cv2.CAP_PROP_POS_FRAMES) progress = int((current_pos / total_frames) * 100) self.progress_updated.emit(progress) self.frame_index = int(current_pos) self.frame_index_updated.emit(self.frame_index)
if not self.is_original and self.detector: boxes, stats = self.detector.detect(frame) self.detector._draw_boxes(frame, boxes) else: stats = {}
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) h, w, ch = rgb.shape qimg = QImage(rgb.data, w, h, ch * w, QImage.Format.Format_RGB888) pixmap = QPixmap.fromImage(qimg) self.update_frame.emit(pixmap, stats) self.msleep(10)
if isinstance(self.source, int): self.camera.release() else: cap.release()
def stop(self): self.running = False
if __name__ == "__main__": app = QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec())
|