Repository navigation
Expand file tree
/
Copy pathProcess_Selection_Dialog.py
More file actions
2300 lines (1875 loc) · 89.7 KB
/
Copy pathProcess_Selection_Dialog.py
File metadata and controls
2300 lines (1875 loc) · 89.7 KB
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import numpy as np
import cv2
import json
import time
from datetime import datetime
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTabWidget, QWidget,
QVBoxLayout, QPushButton, QLabel, QListWidget,
QDialog, QHBoxLayout, QFileDialog, QComboBox,
QSpinBox, QDoubleSpinBox, QCheckBox, QSlider,
QGroupBox, QMessageBox, QInputDialog, QAction,
QMenu, QToolBar, QStatusBar, QSplitter, QFormLayout,
QLineEdit, QListWidgetItem, QSizePolicy, QGraphicsView,
QGraphicsScene, QGraphicsPixmapItem, QGraphicsRectItem,
QGraphicsEllipseItem, QGraphicsTextItem, QColorDialog,
QDockWidget, QTextEdit,QGraphicsPixmapItem)
from PyQt5.QtCore import Qt, QTimer, QSize, QRect, QPoint, QRectF, QEvent,QPointF, QLineF
from PyQt5.QtGui import (QImage, QPixmap, QPainter, QPen, QColor, QIcon,
QFont, QCursor, QBrush, QPolygonF, QFontMetrics)
import dxcam
from skimage import measure
import psutil
import win32gui
import win32process
import win32con
from scipy.interpolate import splprep, splev
from scipy.ndimage import gaussian_filter1d
from collections import deque
from sklearn.cluster import KMeans
from sklearn.linear_model import LinearRegression
import math
class EnhancedGraphicsView(QGraphicsView):
"""增强的图形视图,支持缩放和平移"""
def __init__(self, parent=None):
super().__init__(parent)
self._zoom = 0
self._empty = True
self._scene = QGraphicsScene(self)
self.setScene(self._scene)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setBackgroundBrush(QBrush(QColor(30, 30, 30)))
self.setFrameShape(QGraphicsView.NoFrame)
self.setRenderHint(QPainter.Antialiasing)
def hasImage(self):
return not self._empty
def fitInView(self, scale=True):
rect = QRectF(self._pixmap.rect())
if not rect.isNull():
self.setSceneRect(rect)
if self.hasImage():
unity = self.transform().mapRect(QRectF(0, 0, 1, 1))
self.scale(1 / unity.width(), 1 / unity.height())
viewrect = self.viewport().rect()
scenerect = self.transform().mapRect(rect)
factor = min(viewrect.width() / scenerect.width(),
viewrect.height() / scenerect.height())
self.scale(factor, factor)
self._zoom = 0
def setImage(self, pixmap):
self._zoom = 0
if pixmap.isNull():
self._empty = True
return
self._empty = False
self._pixmap = pixmap
self._scene.clear()
self._scene.addPixmap(self._pixmap)
self.fitInView()
def wheelEvent(self, event):
if self.hasImage():
if event.angleDelta().y() > 0:
factor = 1.25
self._zoom += 1
else:
factor = 0.8
self._zoom -= 1
if self._zoom > 0:
self.scale(factor, factor)
elif self._zoom == 0:
self.fitInView()
else:
self._zoom = 0
class RegionSelectionDialog(QDialog):
"""窗口区域选择对话框"""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("选择捕获区域")
self.setWindowModality(Qt.ApplicationModal)
self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_TranslucentBackground)
# 获取屏幕尺寸
screen = QApplication.primaryScreen().geometry()
self.setGeometry(0, 0, screen.width(), screen.height())
# 选择区域
self.selection_start = None
self.selection_end = None
self.selection_rect = None
self.selected_region = None
# 提示标签
self.label = QLabel("拖动鼠标选择区域,按Enter确认或ESC取消", self)
self.label.setStyleSheet("background-color: rgba(0,0,0,0.7); color: white; padding: 5px;")
self.label.move(10, 10)
def paintEvent(self, event):
painter = QPainter(self)
painter.setPen(QPen(QColor(255, 255, 255, 200), 2))
# 绘制半透明覆盖层
painter.fillRect(self.rect(), QBrush(QColor(0, 0, 0, 100)))
# 绘制选择区域
if self.selection_rect:
painter.fillRect(self.selection_rect, QBrush(QColor(255, 255, 255, 50)))
painter.drawRect(self.selection_rect)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.selection_start = event.pos()
self.selection_end = event.pos()
self.update()
def mouseMoveEvent(self, event):
if self.selection_start:
self.selection_end = event.pos()
self.selection_rect = QRect(self.selection_start, self.selection_end).normalized()
self.update()
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton and self.selection_rect:
self.selected_region = (
self.selection_rect.x(),
self.selection_rect.y(),
self.selection_rect.width(),
self.selection_rect.height()
)
self.accept() # 自动确认选择
class ProcessSelectionDialog(QDialog):
"""增强的进程选择对话框,支持多选"""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("选择目标进程")
self.setWindowModality(Qt.ApplicationModal)
self.resize(600, 500)
self.layout = QVBoxLayout()
# 筛选区域
self.filter_group = QGroupBox("进程筛选")
self.filter_layout = QHBoxLayout()
self.filter_label = QLabel("筛选条件:")
self.filter_combo = QComboBox()
self.filter_combo.addItems(["所有进程", "图形窗口", "高CPU占用", "高内存占用", "置顶窗口"])
self.filter_text = QLineEdit()
self.filter_text.setPlaceholderText("输入进程名...")
self.refresh_btn = QPushButton("刷新")
self.filter_layout.addWidget(self.filter_label)
self.filter_layout.addWidget(self.filter_combo)
self.filter_layout.addWidget(self.filter_text)
self.filter_layout.addWidget(self.refresh_btn)
self.filter_group.setLayout(self.filter_layout)
# 进程列表 (支持多选)
self.process_list = QListWidget()
self.process_list.setSelectionMode(QListWidget.MultiSelection)
self.process_list.setIconSize(QSize(32, 32))
# 详情区域
self.detail_group = QGroupBox("进程详情")
self.detail_layout = QVBoxLayout()
self.detail_label = QLabel("选择进程查看详情")
self.detail_label.setWordWrap(True)
self.detail_layout.addWidget(self.detail_label)
self.detail_group.setLayout(self.detail_layout)
# 按钮区域
self.button_layout = QHBoxLayout()
self.ok_button = QPushButton("确定")
self.cancel_button = QPushButton("取消")
self.button_layout.addStretch()
self.button_layout.addWidget(self.ok_button)
self.button_layout.addWidget(self.cancel_button)
# 主布局
self.layout.addWidget(self.filter_group)
splitter = QSplitter(Qt.Vertical)
splitter.addWidget(self.process_list)
splitter.addWidget(self.detail_group)
self.layout.addWidget(splitter)
self.layout.addLayout(self.button_layout)
self.setLayout(self.layout)
# 真实进程列表
self.processes = []
self.refresh_processes()
# 连接信号
self.ok_button.clicked.connect(self.accept)
self.cancel_button.clicked.connect(self.reject)
self.refresh_btn.clicked.connect(self.refresh_processes)
self.process_list.itemSelectionChanged.connect(self.show_process_detail)
self.filter_combo.currentIndexChanged.connect(self.refresh_processes)
self.filter_text.textChanged.connect(self.refresh_processes)
def get_process_list(self):
"""获取系统进程列表,包含窗口标题和置顶状态"""
process_list = []
def callback(hwnd, extra):
if win32gui.IsWindowVisible(hwnd):
_, pid = win32process.GetWindowThreadProcessId(hwnd)
try:
title = win32gui.GetWindowText(hwnd)
if title: # 只显示有窗口标题的进程
process = psutil.Process(pid)
# 检查窗口是否置顶
style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)
is_topmost = (style & win32con.WS_EX_TOPMOST) != 0
process_info = {
'pid': pid,
'name': process.name(),
'title': title,
'cpu': process.cpu_percent(),
'memory': process.memory_percent(),
'hwnd': hwnd,
'topmost': is_topmost
}
process_list.append(process_info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
# 枚举所有窗口
win32gui.EnumWindows(callback, None)
return process_list
def refresh_processes(self):
self.process_list.clear()
filter_type = self.filter_combo.currentText()
filter_text = self.filter_text.text().lower()
self.processes = self.get_process_list()
for proc in self.processes:
# 筛选条件
if filter_text and filter_text not in proc["name"].lower() and filter_text not in proc["title"].lower():
continue
if filter_type == "高CPU占用" and proc["cpu"] < 5:
continue
if filter_type == "高内存占用" and proc["memory"] < 100:
continue
if filter_type == "置顶窗口" and not proc["topmost"]:
continue
item = QListWidgetItem()
text = f"{proc['title']} ({proc['name']} - PID: {proc['pid']})"
if proc['topmost']:
text += " [置顶]"
item.setText(text)
item.setIcon(QIcon.fromTheme("application-x-executable"))
item.setData(Qt.UserRole, proc)
self.process_list.addItem(item)
def show_process_detail(self):
selected = self.process_list.selectedItems()
if not selected:
return
proc = selected[0].data(Qt.UserRole)
details = f"""
<b>窗口标题:</b> {proc['title']}<br>
<b>进程名称:</b> {proc['name']}<br>
<b>进程ID:</b> {proc['pid']}<br>
<b>CPU占用:</b> {proc['cpu']:.1f}%<br>
<b>内存占用:</b> {proc['memory']:.1f} MB<br>
<b>窗口状态:</b> {"置顶" if proc['topmost'] else "普通"}<br>
"""
self.detail_label.setText(details)
def selected_processes(self):
"""返回选中的进程列表"""
selected = []
for item in self.process_list.selectedItems():
selected.append(item.data(Qt.UserRole))
return selected
class TrajectoryAnalyzer:
"""轨迹分析工具类"""
def __init__(self):
self.trajectories = []
self.smooth_cache = {}
def add_trajectory(self, points):
"""添加一条轨迹"""
self.trajectories.append(points)
def smooth_trajectory(self, points, sigma=3):
"""使用高斯滤波平滑轨迹"""
if len(points) < 3:
return points
# 检查缓存
cache_key = hash(tuple(points))
if cache_key in self.smooth_cache:
return self.smooth_cache[cache_key]
x = [p[0] for p in points]
y = [p[1] for p in points]
# 应用高斯滤波
x_smooth = gaussian_filter1d(x, sigma=sigma)
y_smooth = gaussian_filter1d(y, sigma=sigma)
smoothed = list(zip(x_smooth, y_smooth))
self.smooth_cache[cache_key] = smoothed
return smoothed
def calculate_velocity(self, points):
"""计算轨迹点的速度"""
if len(points) < 2:
return []
velocities = []
for i in range(1, len(points)):
dx = points[i][0] - points[i-1][0]
dy = points[i][1] - points[i-1][1]
distance = np.sqrt(dx**2 + dy**2)
velocities.append(distance) # 像素/帧
return velocities
def calculate_acceleration(self, velocities):
"""计算加速度"""
if len(velocities) < 2:
return []
accelerations = []
for i in range(1, len(velocities)):
accelerations.append(velocities[i] - velocities[i-1]) # 像素/帧²
return accelerations
def predict_path(self, points, steps=10):
"""预测未来路径(简单线性回归)"""
if len(points) < 3:
return []
x = np.array([p[0] for p in points]).reshape(-1, 1)
y = np.array([p[1] for p in points]).reshape(-1, 1)
model_x = LinearRegression()
model_y = LinearRegression()
time_steps = np.array(range(len(points))).reshape(-1, 1)
model_x.fit(time_steps, x)
model_y.fit(time_steps, y)
future_steps = np.array(range(len(points), len(points)+steps)).reshape(-1, 1)
future_x = model_x.predict(future_steps)
future_y = model_y.predict(future_steps)
return list(zip(future_x.flatten(), future_y.flatten()))
def cluster_trajectories(self, n_clusters=3):
"""对多条轨迹进行聚类"""
if not self.trajectories:
return []
# 提取特征: 每条轨迹的平均x,y和长度
features = []
for traj in self.trajectories:
if not traj:
continue
x = [p[0] for p in traj]
y = [p[1] for p in traj]
features.append([
np.mean(x), np.mean(y), len(traj)
])
if len(features) < n_clusters:
return [0] * len(features)
kmeans = KMeans(n_clusters=n_clusters)
clusters = kmeans.fit_predict(features)
return clusters
def generate_heatmap(self, width, height, sigma=15):
"""生成热力图"""
heatmap = np.zeros((height, width))
for traj in self.trajectories:
for x, y in traj:
if 0 <= x < width and 0 <= y < height:
heatmap[int(y), int(x)] += 1
# 应用高斯模糊
heatmap = cv2.GaussianBlur(heatmap, (0, 0), sigma)
# 归一化
if heatmap.max() > 0:
heatmap = heatmap / heatmap.max()
return heatmap
class MotionDetector:
"""增强的运动检测器,支持多种算法"""
def __init__(self):
self.prev_frame = None
self.prev_gray = None
self.min_contour_area = 100
self.threshold = 25
self.detection_roi = None # (x, y, w, h)
self.detection_method = "frame_diff" # frame_diff, background_sub, optical_flow
self.background_model = None
self.background_alpha = 0.05 # 背景模型学习率
self.optical_flow_params = dict(
winSize=(15, 15),
maxLevel=2,
criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)
)
self.tracked_points = None
self.tracking_colors = None
def set_roi(self, roi):
"""设置检测区域"""
self.detection_roi = roi
def set_method(self, method):
"""设置检测方法"""
self.detection_method = method
def detect(self, frame):
"""检测运动物体"""
if frame is None:
return []
# 转换为灰度图
gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
# 应用ROI
if self.detection_roi:
x, y, w, h = self.detection_roi
gray = gray[y:y+h, x:x+w]
frame_roi = frame[y:y+h, x:x+w]
else:
frame_roi = frame
motion_centers = []
if self.detection_method == "frame_diff":
motion_centers = self._frame_diff(gray)
elif self.detection_method == "background_sub":
motion_centers = self._background_subtraction(gray)
elif self.detection_method == "optical_flow":
motion_centers = self._optical_flow(frame_roi, gray)
# 如果有ROI,调整坐标
if self.detection_roi and motion_centers:
motion_centers = [(x + self.detection_roi[0], y + self.detection_roi[1])
for (x, y) in motion_centers]
return motion_centers
def _frame_diff(self, gray):
"""帧差法检测运动"""
if self.prev_frame is None:
self.prev_frame = gray
return []
# 计算帧差
frame_diff = cv2.absdiff(gray, self.prev_frame)
self.prev_frame = gray
# 二值化
_, threshold = cv2.threshold(frame_diff, self.threshold, 255, cv2.THRESH_BINARY)
# 膨胀处理
kernel = np.ones((5, 5), np.uint8)
threshold = cv2.dilate(threshold, kernel, iterations=1)
# 查找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 过滤小轮廓
motion_centers = []
for cnt in contours:
if cv2.contourArea(cnt) > self.min_contour_area:
# 计算轮廓中心
M = cv2.moments(cnt)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
motion_centers.append((cx, cy))
return motion_centers
def _background_subtraction(self, gray):
"""背景减除法检测运动"""
if self.background_model is None:
self.background_model = gray.copy().astype(np.float32)
return []
# 更新背景模型
cv2.accumulateWeighted(gray, self.background_model, self.background_alpha)
# 计算与背景的差异
background = self.background_model.astype(np.uint8)
frame_diff = cv2.absdiff(gray, background)
# 二值化
_, threshold = cv2.threshold(frame_diff, self.threshold, 255, cv2.THRESH_BINARY)
# 膨胀处理
kernel = np.ones((5, 5), np.uint8)
threshold = cv2.dilate(threshold, kernel, iterations=1)
# 查找轮廓
contours, _ = cv2.findContours(threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 过滤小轮廓
motion_centers = []
for cnt in contours:
if cv2.contourArea(cnt) > self.min_contour_area:
M = cv2.moments(cnt)
if M["m00"] != 0:
cx = int(M["m10"] / M["m00"])
cy = int(M["m01"] / M["m00"])
motion_centers.append((cx, cy))
return motion_centers
def _optical_flow(self, frame, gray):
"""光流法检测运动"""
if self.prev_gray is None:
self.prev_gray = gray
# 初始化跟踪点
feature_params = dict(
maxCorners=100,
qualityLevel=0.3,
minDistance=7,
blockSize=7
)
self.tracked_points = cv2.goodFeaturesToTrack(gray, mask=None, **feature_params)
self.tracking_colors = np.random.randint(0, 255, (100, 3))
return []
# 计算光流
new_points, status, _ = cv2.calcOpticalFlowPyrLK(
self.prev_gray, gray, self.tracked_points, None, **self.optical_flow_params)
# 只保留好的点
good_new = new_points[status == 1]
good_old = self.tracked_points[status == 1]
# 更新跟踪点
self.tracked_points = good_new.reshape(-1, 1, 2)
self.prev_gray = gray.copy()
# 计算运动向量
motion_centers = []
for i, (new, old) in enumerate(zip(good_new, good_old)):
a, b = new.ravel()
c, d = old.ravel()
# 计算运动距离
distance = np.sqrt((a-c)**2 + (b-d)**2)
if distance > 2: # 移动超过2像素才认为是运动
motion_centers.append((int(a), int(b)))
return motion_centers
class TrajectoryWidget(QWidget):
"""增强的轨迹显示部件,支持所有新功能"""
def __init__(self):
super().__init__()
self.trajectory_points = [] # 存储所有轨迹点
self.current_frame = None # 当前帧图像
self.trajectory_colors = [] # 不同轨迹颜色
self.active_trajectory = 0 # 当前活动轨迹索引
self.show_trajectory = True # 是否显示轨迹
self.show_points = True # 是否显示轨迹点
self.show_info = True # 是否显示信息
self.grid_size = 50 # 网格大小
self.show_grid = False # 是否显示网格
self.measure_points = [] # 测量点
self.measure_mode = False # 是否处于测量模式
self.annotation_mode = False # 是否处于标注模式
self.annotations = [] # 存储所有标注
self.heatmap = None # 热力图数据
self.show_heatmap = False # 是否显示热力图
self.velocity_vectors = [] # 速度向量
self.show_velocity = False # 是否显示速度
self.predicted_paths = [] # 预测路径
self.show_prediction = False # 是否显示预测路径
self.smooth_trajectory = False # 是否平滑轨迹
self.trajectory_analyzer = TrajectoryAnalyzer() # 轨迹分析器
self.heatmap_cache = None # 热力图缓存
self.last_heatmap_time = 0 # 上次计算时间戳
self.setMouseTracking(True)
self.setMinimumSize(640, 480)
# 初始化颜色生成器
self.color_index = 0
self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
def toggleHeatmap(self, show=None):
"""切换热力图显示状态"""
if show is None:
self.show_heatmap = not self.show_heatmap
else:
self.show_heatmap = show
self.update()
def get_next_color(self):
"""生成视觉区分度极高的HSV颜色(支持上千条轨迹)"""
# 可调参数(根据需求自定义)
GOLDEN_ANGLE = 137.508 # 黄金角分散色相
SATURATION_RANGE = (180, 255) # 饱和度范围(避免灰暗)
VALUE_RANGE = (200, 255) # 明度范围(避免太暗)
HUE_STEP = 10 # 基础色相步长(可减小以增加颜色数量)
# 动态计算HSV值
hue = (self.color_index * GOLDEN_ANGLE) % 360 # 使用黄金角分散色相
saturation = SATURATION_RANGE[1] - (self.color_index % 5) * 15 # 饱和度波动
value = VALUE_RANGE[1] - (self.color_index % 3) * 20 # 明度波动
# 确保数值在有效范围内
saturation = max(min(saturation, SATURATION_RANGE[1]), SATURATION_RANGE[0])
value = max(min(value, VALUE_RANGE[1]), VALUE_RANGE[0])
# 更新索引
self.color_index += 1
return QColor.fromHsv(int(hue), int(saturation), int(value))
def setFrame(self, frame):
"""设置当前帧图像"""
self.current_frame = frame
self.update()
def addPoint(self, point, trajectory_idx=0):
"""添加轨迹点"""
while len(self.trajectory_points) <= trajectory_idx:
self.trajectory_points.append([])
self.trajectory_points[trajectory_idx].append(point)
# 更新分析器
if len(self.trajectory_points[trajectory_idx]) > 1:
self.trajectory_analyzer.add_trajectory(self.trajectory_points[trajectory_idx])
# 计算速度
if len(self.trajectory_points[trajectory_idx]) > 2:
velocities = self.trajectory_analyzer.calculate_velocity(
self.trajectory_points[trajectory_idx])
if velocities:
last_point = self.trajectory_points[trajectory_idx][-1]
prev_point = self.trajectory_points[trajectory_idx][-2]
dx = last_point[0] - prev_point[0]
dy = last_point[1] - prev_point[1]
self.velocity_vectors.append((
prev_point[0], prev_point[1], dx, dy, velocities[-1]))
self.update()
def clearTrajectory(self, trajectory_idx=None):
"""清除轨迹"""
if trajectory_idx is None:
self.trajectory_points = []
self.velocity_vectors = []
self.predicted_paths = []
self.trajectory_analyzer = TrajectoryAnalyzer()
else:
if trajectory_idx < len(self.trajectory_points):
self.trajectory_points[trajectory_idx] = []
self.update()
def startMeasure(self):
"""开始测量"""
self.measure_mode = not self.measure_mode
if not self.measure_mode:
self.measure_points = []
self.update()
self.setCursor(Qt.CrossCursor)
def startAnnotation(self):
"""开始标注"""
self.annotation_mode = not self.annotation_mode
if not self.annotation_mode:
pass
self.update()
self.setCursor(Qt.CrossCursor)
def addAnnotation(self, annotation):
"""添加标注"""
self.annotations.append(annotation)
self.update()
def clearAnnotations(self):
"""清除所有标注"""
self.annotations = []
self.update()
def generateHeatmap(self):
"""生成热力图(带缓存和性能优化)"""
# 检查是否有任何轨迹点
if not any(self.trajectory_points) or self.current_frame is None:
return
# 仅在轨迹变化或超过1秒未更新时重新计算
current_time = time.time()
if (self.heatmap_cache is None or
current_time - self.last_heatmap_time > 1.0):
height, width = self.current_frame.shape[:2]
# 使用半分辨率计算提升性能
small_width, small_height = width//2, height//2
heatmap = np.zeros((small_height, small_width), dtype=np.float32)
# 聚合轨迹点(向量化操作)
for traj in self.trajectory_points:
if traj: # 跳过空轨迹
points = np.array(traj) * [small_width/width, small_height/height]
points = points.astype(np.int32)
valid = (points[:,0] >= 0) & (points[:,0] < small_width) & \
(points[:,1] >= 0) & (points[:,1] < small_height)
np.add.at(heatmap, (points[valid,1], points[valid,0]), 1)
# 高斯模糊并归一化
if heatmap.max() > 0:
heatmap = cv2.GaussianBlur(heatmap, (0,0), 15)
heatmap /= heatmap.max()
self.heatmap_cache = cv2.resize(heatmap, (width, height))
self.last_heatmap_time = current_time
self.show_heatmap = True
self.update()
def toggleVelocity(self, show):
"""切换速度显示"""
self.show_velocity = show
self.update()
def togglePrediction(self, show):
"""切换预测路径显示"""
self.show_prediction = show
if show and self.trajectory_points:
self.predicted_paths = []
for traj in self.trajectory_points:
if len(traj) > 10: # 只有足够长的轨迹才预测
self.predicted_paths.append(
self.trajectory_analyzer.predict_path(traj))
self.update()
def toggleSmoothTrajectory(self, smooth):
"""切换轨迹平滑"""
self.smooth_trajectory = smooth
self.update()
def mergeTrajectories(self, indices):
"""合并多条轨迹"""
if len(indices) < 2:
return
merged = []
for idx in indices:
if idx < len(self.trajectory_points):
merged.extend(self.trajectory_points[idx])
self.trajectory_points[idx] = []
# 添加合并后的轨迹
self.trajectory_points.append(merged)
self.update()
def splitTrajectory(self, trajectory_idx, split_index):
"""分割轨迹"""
if trajectory_idx >= len(self.trajectory_points):
return
traj = self.trajectory_points[trajectory_idx]
if split_index >= len(traj):
return
# 分割为两条轨迹
first_part = traj[:split_index]
second_part = traj[split_index:]
self.trajectory_points[trajectory_idx] = first_part
self.trajectory_points.append(second_part)
self.update()
def mousePressEvent(self, event):
if self.measure_mode and event.button() == Qt.LeftButton:
pos = event.pos()
if hasattr(self, 'display_rect') and self.display_rect.contains(pos):
rel_x = pos.x() - self.display_rect.x()
rel_y = pos.y() - self.display_rect.y()
img_x = int(rel_x * self.current_frame.shape[1] / self.display_rect.width())
img_y = int(rel_y * self.current_frame.shape[0] / self.display_rect.height())
self.measure_points.append((img_x, img_y))
self.update()
elif self.annotation_mode and event.button() == Qt.LeftButton:
pos = event.pos()
if hasattr(self, 'display_rect') and self.display_rect.contains(pos):
rel_x = pos.x() - self.display_rect.x()
rel_y = pos.y() - self.display_rect.y()
img_x = int(rel_x * self.current_frame.shape[1] / self.display_rect.width())
img_y = int(rel_y * self.current_frame.shape[0] / self.display_rect.height())
# 弹出对话框获取标注文本
text, ok = QInputDialog.getText(self, "添加标注", "输入标注文本:")
if ok and text:
self.addAnnotation({
'x': img_x,
'y': img_y,
'text': text,
'color': QColor(255, 255, 0)
})
def mouseMoveEvent(self, event):
if self.measure_mode or self.annotation_mode:
self.update()
def paintEvent(self, event):
if self.current_frame is None:
return
painter = QPainter(self)
# 绘制背景
painter.fillRect(self.rect(), QBrush(QColor(255, 255, 255)))
# 绘制当前帧
height, width, channels = self.current_frame.shape
bytes_per_line = 3 * width
q_img = QImage(self.current_frame.data, width, height, bytes_per_line, QImage.Format_RGB888)
# 计算缩放后的尺寸,保持宽高比
img_ratio = width / height
widget_ratio = self.width() / self.height()
if img_ratio > widget_ratio:
display_width = self.width()
display_height = int(display_width / img_ratio)
else:
display_height = self.height()
display_width = int(display_height * img_ratio)
# 居中显示
x_offset = (self.width() - display_width) // 2
y_offset = (self.height() - display_height) // 2
self.display_rect = QRect(x_offset, y_offset, display_width, display_height)
painter.drawPixmap(self.display_rect, QPixmap.fromImage(q_img))
# 绘制热力图 - 只保留这一段
if self.show_heatmap and self.heatmap_cache is not None:
# 使用OpenCV的Jet颜色映射
heatmap_color = cv2.applyColorMap(
np.uint8(self.heatmap_cache * 255),
cv2.COLORMAP_JET
)
heatmap_color = cv2.cvtColor(heatmap_color, cv2.COLOR_BGR2RGB)
heatmap_qimg = QImage(
heatmap_color.data,
heatmap_color.shape[1],
heatmap_color.shape[0],
3 * heatmap_color.shape[1],
QImage.Format_RGB888
)
painter.setOpacity(0.5)
painter.drawPixmap(self.display_rect, QPixmap.fromImage(heatmap_qimg))
painter.setOpacity(1.0)
# 绘制网格
if self.show_grid and self.display_rect.width() > 0:
pen = QPen(QColor(255, 255, 255, 50), 1, Qt.DotLine)
painter.setPen(pen)
x_line = int(display_width / self.grid_size) + 1
y_line = int(display_height / self.grid_size) + 1
for i in range(x_line):
x = x_offset + i * self.grid_size
painter.drawLine(x, y_offset, x, y_offset + display_height)
for i in range(y_line):
y = y_offset + i * self.grid_size
painter.drawLine(x_offset, y, x_offset + display_width, y)
# 绘制轨迹
if self.show_trajectory:
for traj_idx, trajectory in enumerate(self.trajectory_points):
if len(trajectory) > 1:
# 确保有足够的颜色,如果没有则生成新的
while traj_idx >= len(self.trajectory_colors):
self.trajectory_colors.append(self.get_next_color())
color = self.trajectory_colors[traj_idx]
pen = QPen(color, 3)
painter.setPen(pen)
# 选择原始轨迹或平滑轨迹
points_to_draw = trajectory
if self.smooth_trajectory:
points_to_draw = self.trajectory_analyzer.smooth_trajectory(trajectory)
# 绘制轨迹线
for i in range(1, len(points_to_draw)):
prev_point = self._imageToWindow(points_to_draw[i-1])
curr_point = self._imageToWindow(points_to_draw[i])
if prev_point and curr_point:
painter.drawLine(prev_point, curr_point)
# 绘制轨迹点
if self.show_points:
point_pen = QPen(color, 1)
painter.setPen(point_pen)
brush = QBrush(color)
painter.setBrush(brush)
for point in points_to_draw:
win_point = self._imageToWindow(point)
if win_point:
painter.drawEllipse(win_point, 3, 3)
# 绘制速度向量
if self.show_velocity and self.velocity_vectors:
for x, y, dx, dy, speed in self.velocity_vectors:
start = self._imageToWindow((x, y))
end = self._imageToWindow((x + dx, y + dy))
if start and end:
# 根据速度大小设置颜色 (慢-绿, 快-红)
speed_color = QColor(
min(255, int(speed * 10)),
max(0, 255 - int(speed * 10)),
0
)
pen = QPen(speed_color, 2)
painter.setPen(pen)
painter.drawLine(start, end)
# 绘制箭头
angle = np.arctan2(end.y() - start.y(), end.x() - start.x())
arrow_size = 10
arrow_p1 = end - QPoint(
int(arrow_size * np.cos(angle - np.pi / 6)),
int(arrow_size * np.sin(angle - np.pi / 6))
)
arrow_p2 = end - QPoint(
int(arrow_size * np.cos(angle + np.pi / 6)),
int(arrow_size * np.sin(angle + np.pi / 6))
)
painter.drawLine(end, arrow_p1)
painter.drawLine(end, arrow_p2)
# 绘制预测路径
if self.show_prediction and self.predicted_paths:
for i, path in enumerate(self.predicted_paths):
if len(path) > 1:
color = self.trajectory_colors[i % len(self.trajectory_colors)]
pen = QPen(color, 2, Qt.DashLine)
painter.setPen(pen)