-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathRookieAI.py
2548 lines (2196 loc) · 117 KB
/
RookieAI.py
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 contextlib
import math
import multiprocessing
import os
import queue
import subprocess
import sys
import time
import cv2
import mss
import numpy as np
import pyautogui
import win32api
import win32con
from math import sqrt
from ultralytics import YOLO
from PyQt6 import QtWidgets, uic
from PyQt6.QtCore import QTimer, Qt, QPropertyAnimation, QPoint, QEasingCurve, QParallelAnimationGroup, QRect, QSize
from PyQt6.QtGui import QIcon, QImage, QPixmap, QBitmap, QPainter
from PyQt6.QtWidgets import QGraphicsOpacityEffect, QFileDialog, QMessageBox, QSizePolicy
from multiprocessing import Pipe, Process, Queue, shared_memory, Event
from customLib.animated_status import AnimatedStatus # 导入 带动画的状态提示浮窗 库
from Module.const import method_mode
from Module.config import Config, Root
from Module.control import kmNet
from Module.logger import logger
import Module.control as control
import Module.keyboard as keyboard
import Module.jump_detection as jump_detection
import Module.announcement
def communication_Process(pipe, videoSignal_queue, videoSignal_stop_queue, floating_information_signal_queue,
information_output_queue):
"""
总通信进程
pipe_parent
"""
global video_running
logger.debug("启动 communication_Process 监听信号...")
while True:
if pipe.poll():
try:
message = pipe.recv()
if isinstance(message, tuple): # 处理消息类型
cmd, cmd_01 = message
logger.debug(f"收到信号: {cmd}")
logger.debug(f"信号内容: {cmd_01}")
information_output_queue.put(
("log_output_main", message)) # 显示调试信息
# 手动触发异常测试
if cmd == "trigger_error":
logger.info("手动触发异常测试")
raise ValueError("[INFO]手动触发的错误")
if cmd == "start_video":
logger.info("启动视频命令")
video_running = True
videoSignal_queue.put(("start_video", cmd_01))
elif cmd == "stop_video":
logger.info("停止视频命令")
video_running = False
videoSignal_stop_queue.put(("stop_video", cmd_01))
elif cmd == "loading_complete":
logger.info("软件初始化完毕")
floating_information_signal_queue.put(
("loading_complete", cmd_01))
elif cmd == "loading_error":
logger.error("一般错误,软件初始化失败")
floating_information_signal_queue.put(
("error_log", cmd_01))
elif cmd == "red_error":
logger.fatal("致命错误,无法加载模型")
floating_information_signal_queue.put(
("red_error_log", cmd_01))
except (BrokenPipeError, EOFError) as e:
logger.error(f"管道通信错误: {e}")
information_output_queue.put(
("error_log", f"管道通信错误: {e}")) # 捕获并记录错误信息
except Exception as e:
logger.error(f"发生错误: {e}")
information_output_queue.put(("error_log", f"未知错误: {e}"))
def start_capture_process_multie(shm_name, frame_shape, frame_dtype, frame_available_event,
videoSignal_queue, videoSignal_stop_queue, pipe, information_output_queue,
ProcessMode):
"""
(多进程)
子进程视频信号获取逻辑 \n
接收内容:\n
1.start_video \n
2.stop_video
"""
# 连接到共享内存
existing_shm = shared_memory.SharedMemory(name=shm_name)
shared_frame = np.ndarray(
frame_shape, dtype=frame_dtype, buffer=existing_shm.buf)
logger.debug("视频信号获取进程已启动。")
while True:
try:
message = videoSignal_queue.get(timeout=1)
command, information = message
logger.debug(f"接收到命令: {command}, 内容: {information}")
information_output_queue.put(
("video_signal_acquisition_log", message)) # 调试信息输出
if command == "start_video":
logger.debug("进程模式选择")
logger.info("进程模式:", ProcessMode)
open_screen_video(
shared_frame, frame_available_event, videoSignal_stop_queue)
if command == "change_model":
logger.info("正在重新加载模型")
model_file = information
model = YOLO(model_file)
logger.info(f"模型 {model_file} 加载完毕")
except queue.Empty:
pass
except Exception as e:
logger.error(f"获取视频信号时发生错误: {e}")
information_output_queue.put(("error_log", f"获取视频信号时发生错误: {e}"))
def start_capture_process_single(videoSignal_queue, videoSignal_stop_queue, information_output_queue,
processedVideo_queue, YoloSignal_queue, pipe_parent, model_file,
box_shm_name, box_data_event, box_lock):
"""
(单进程)子进程视频信号获取逻辑
接收内容:
1.start_video
2.stop_video
"""
logger.debug("视频信号获取进程已启动。")
def initialization_Yolo(model_file, information_output_queue):
"""初始化 YOLO 并进行一次模拟推理"""
try:
# 检查模型文件是否存在
if not os.path.exists(model_file):
logger.warn(f"模型文件 '{model_file}' 未找到,尝试使用默认模型 'yolov8n.pt'。")
information_output_queue.put(
("log_output_main", f"模型文件 '{model_file}' 未找到,使用默认模型 yolov8n.pt'。"))
model_file = "yolov8n.pt"
log_message = f"[ERROR]一般错误,模型文件 '{model_file}' 未找到,使用默认模型 'yolov8n.pt'。"
# 选定文件未能找到,黄色报错
pipe_parent.send(("loading_error", log_message))
if not os.path.exists(model_file):
logger.fatal(f"致命错误,默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。")
log_message = f"[ERROR]致命错误,默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。"
# 默认文件也未找到,红色报错
pipe_parent.send(("red_error", log_message))
raise FileNotFoundError(
f"默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。")
model = YOLO(model_file) # 加载 YOLO 模型
logger.info(f"YOLO 模型 '{model_file}' 已加载。")
# 创建一张临时图像(纯色或随机噪声)用于预热
temp_img = np.zeros((320, 320, 3), dtype=np.uint8) # 修改为640x640
temp_img_path = "temp_init_image.jpg"
cv2.imwrite(temp_img_path, temp_img)
# 执行一次模拟推理
model.predict(temp_img_path, conf=0.5)
logger.debug("YOLO 模型已预热完成。")
os.remove(temp_img_path) # 删除临时图像
return model
except Exception as e:
logger.error(f"YOLO 初始化失败: {e}")
information_output_queue.put(("error_log", f"YOLO 初始化失败: {e}"))
return None
model = initialization_Yolo(
model_file, information_output_queue) # 初始化YOLO
pipe_parent.send(("loading_complete", True)) # 初始化加载完成标志
with contextlib.suppress(KeyboardInterrupt):
while True:
"""开始监听视频开关信号"""
try:
message = videoSignal_queue.get(timeout=1)
command, information = message
logger.debug(f"接收到命令: {command}, 内容: {information}")
information_output_queue.put(
("video_signal_acquisition_log", message)) # 调试信息输出
if command == 'start_video':
logger.debug("启动视频捕获和YOLO处理")
# 调用集成了共享内存写入的屏幕捕获和YOLO处理函数
screen_capture_and_yolo_processing(
processedVideo_queue, videoSignal_stop_queue, YoloSignal_queue,
pipe_parent, information_output_queue, model,
box_shm_name, box_data_event, box_lock
)
if command == 'change_model': # 重新加载模型
logger.info("正在重新加载模型")
model_file = information
model = YOLO(model_file)
logger.info(f"模型 {model_file} 加载完毕")
except queue.Empty:
pass
except Exception as e:
logger.error(f"获取视频信号时发生错误: {e}")
information_output_queue.put(
("error_log", f"获取视频信号时发生错误: {e}"))
def open_screen_video(shared_frame, frame_available_event, videoSignal_stop_queue):
"""(多进程)打开屏幕捕获并显示视频帧,限制截图速率为100 FPS"""
# 清空 videoSignal_stop_queue 队列
while not videoSignal_stop_queue.empty():
try:
videoSignal_stop_queue.get_nowait()
except Exception:
break
with mss.mss() as sct:
_extracted_from_open_screen_video_11(
videoSignal_stop_queue, sct, shared_frame, frame_available_event
)
# TODO Rename this here and in `open_screen_video`
def _extracted_from_open_screen_video_11(videoSignal_stop_queue, sct, shared_frame, frame_available_event):
# 获取屏幕分辨率
screen_width, screen_height = pyautogui.size()
logger.info("屏幕分辨率:", screen_width, screen_height)
# 计算中心区域 320x320 的截取范围
capture_width, capture_height = 320, 320
left = (screen_width - capture_width) // 2
top = (screen_height - capture_height) // 2
capture_area = {
"top": top,
"left": left,
"width": capture_width,
"height": capture_height
}
# 初始化 'frame' 以避免引用前未赋值
frame = np.zeros((capture_height, capture_width, 3), dtype=np.uint8)
frame_interval = 0.05
while True:
frame_start_time = time.time() # 记录帧开始时间
# 检查是否收到停止信号
if not videoSignal_stop_queue.empty():
command, _ = videoSignal_stop_queue.get()
logger.debug(f"videoSignal_stop_queue(多进程) 队列接收信息 {command}")
if command == 'stop_video':
logger.debug("停止屏幕捕获")
break # 退出循环
# 获取指定区域的截图
img = sct.grab(capture_area)
# 使用 numpy.frombuffer 直接转换为数组,避免数据拷贝
frame = np.frombuffer(img.rgb, dtype=np.uint8)
frame = frame.reshape((img.height, img.width, 3))
# 转换颜色空间,从 BGRA 到 RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGB)
# 将视频帧放入共享内存
np.copyto(shared_frame, frame)
frame_available_event.set()
# 计算已用时间
frame_end_time = time.time()
elapsed_time = frame_end_time - frame_start_time
# 计算剩余时间
remaining_time = frame_interval - elapsed_time
if remaining_time > 0:
time.sleep(remaining_time)
else:
# 如果处理时间超过了帧间隔,可能需要记录或优化
logger.warn(
f"视频帧处理时间 {elapsed_time:.4f} 秒超过目标间隔 {frame_interval:.4f} 秒")
def screen_capture_and_yolo_processing(processedVideo_queue, videoSignal_stop_queue, YoloSignal_queue, pipe_parent,
information_output_queue, model,
box_shm_name, box_data_event, box_lock):
"""
(单进程)整合屏幕捕获和 YOLO 推理。
参数:
- processedVideo_queue: 处理后的视频队列
- videoSignal_stop_queue: 视频停止信号队列
- YoloSignal_queue: YOLO 控制队列
- pipe_parent: 管道父端
- information_output_queue: 调试信息输出队列
- model: YOLO 模型实例
- box_shm_name: Box 坐标共享内存名称
- box_data_event: 用于通知 Box 数据可用的 Event
- box_lock: 用于同步访问共享内存的 Lock
"""
global unique_id_counter
yolo_enabled = False
yolo_confidence = 0.5 # 初始化 YOLO 置信度
unique_id_counter = 0
# 清空 videoSignal_stop_queue 队列
while not videoSignal_stop_queue.empty():
try:
videoSignal_stop_queue.get_nowait()
except Exception:
break
with mss.mss(backend='directx') as sct:
# 获取屏幕分辨率
screen_width, screen_height = pyautogui.size()
logger.info("屏幕分辨率:", screen_width, screen_height)
# 计算中心区域 320x320 的截取范围
capture_width, capture_height = 320, 320
left = (screen_width - capture_width) // 2
top = (screen_height - capture_height) // 2
capture_area = {
"top": top,
"left": left,
"width": capture_width,
"height": capture_height
}
while True:
try:
# 检查是否收到停止信号
if not videoSignal_stop_queue.empty():
command, _ = videoSignal_stop_queue.get()
logger.debug(f"videoSignal_stop_queue(单进程) 队列接收信息 {command}")
if command == 'stop_video':
logger.debug("停止屏幕捕获")
break
if command == 'change_model':
logger.debug("重新加载模型")
break
# 检查 YOLO 的开启或停止信号
if not YoloSignal_queue.empty():
command_data = YoloSignal_queue.get()
if isinstance(command_data, tuple):
cmd, cmd_01 = command_data
information_output_queue.put(
("video_processing_log", command_data))
if cmd == 'YOLO_start':
yolo_enabled = True
elif cmd == 'YOLO_stop':
yolo_enabled = False
elif cmd == "change_conf": # 更改置信度
logger.debug("更改置信度")
yolo_confidence = cmd_01
elif cmd == "change_class":
logger.debug(f"更改检测类别为: {cmd_01}")
target_class = cmd_01 # 更新目标类别
elif cmd == "aim_range_change":
aim_range = cmd_01
logger.debug(f"瞄准范围更改_02: {aim_range}")
# 获取屏幕帧
img = sct.grab(capture_area)
# 转换为 numpy 数组
frame = np.frombuffer(img.rgb, dtype=np.uint8).reshape(
(img.height, img.width, 3))
# 转换颜色空间从 BGRA 到 RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2RGB)
# 如果启用了 YOLO,执行推理并写入共享内存
if yolo_enabled and model is not None:
processed_frame = YOLO_process_frame(
model, frame, yolo_confidence,
target_class=target_class, # 使用更新后的目标类别
box_shm_name=box_shm_name,
box_data_event=box_data_event,
box_lock=box_lock,
aim_range=aim_range,
)
else:
processed_frame = frame
# 将处理后的帧放入队列中
processedVideo_queue.put(processed_frame)
except Exception as e:
logger.warn(f"捕获或处理时出错: {e}")
information_output_queue.put(("error_log", f"捕获或处理时出错: {e}"))
break
def video_processing(shm_name, frame_shape, frame_dtype, frame_available_event,
processedVideo_queue, YoloSignal_queue, pipe_parent, information_output_queue, model_file,
box_shm_name, box_data_event, box_lock):
"""
(多进程)对视频进行处理,支持 YOLO 推理。
参数:
- shm_name: 视频帧共享内存名称
- frame_shape: 视频帧形状
- frame_dtype: 视频帧数据类型
- frame_available_event: 用于通知新帧可用的 Event
- processedVideo_queue: 处理后的视频队列
- YoloSignal_queue: YOLO 控制队列
- pipe_parent: 管道父端
- information_output_queue: 调试信息输出队列
- model_file: YOLO 模型文件路径
- box_shm_name: Box 坐标共享内存名称
- box_data_event: 用于通知 Box 数据可用的 Event
- box_lock: 用于同步访问共享内存的 Lock
"""
global unique_id_counter
yolo_enabled = False
model = None
frame = None
yolo_confidence = 0.5
target_class = "ALL" # 初始化目标类别
unique_id_counter = 0
aim_range = 20 # 瞄准范围默认值
# 连接到共享内存
existing_shm = shared_memory.SharedMemory(name=shm_name)
shared_frame = np.ndarray(
frame_shape, dtype=frame_dtype, buffer=existing_shm.buf)
try:
# 初始化 YOLO
# 检查模型文件是否存在,如果不存在则使用默认模型
if not os.path.exists(model_file):
logger.warn(f"模型文件 '{model_file}' 未找到,尝试使用默认模型 'yolov8n.pt'")
information_output_queue.put(
("log_output_main", f"模型文件 '{model_file}' 未找到,使用默认模型 'yolov8n.pt'。"))
log_message = f"[ERROR]一般错误,模型文件 '{model_file}' 未找到,使用默认模型 'yolov8n.pt'。"
pipe_parent.send(("loading_error", log_message)) # 选定文件未能找到,黄色报错
model_file = "yolov8n.pt"
if not os.path.exists(model_file):
logger.fatal(f"致命错误,默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。")
log_message = f"[ERROR]致命错误,默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。"
pipe_parent.send(("red_error", log_message)) # 默认文件也未找到,红色报错
raise FileNotFoundError(
f"默认模型文件 '{model_file}' 也未找到。请确保模型文件存在。")
model = YOLO(model_file)
logger.debug("YOLO 模型已加载。")
# 进行一次模拟推理以预热模型
temp_img = np.zeros((320, 320, 3), dtype=np.uint8)
model.predict(temp_img, conf=0.5)
logger.debug("YOLO 模型已预热完成。")
pipe_parent.send(("loading_complete", True)) # 软件初始化加载完毕标志
while True:
# 检查 YoloSignal_queue 中的信号
if not YoloSignal_queue.empty():
command_data = YoloSignal_queue.get()
if isinstance(command_data, tuple):
cmd, cmd_01 = command_data
logger.debug(
f"video_processing(YoloSignal_queue) 收到命令: {cmd}, 信息: {cmd_01}")
information_output_queue.put(
("video_processing_log", command_data)) # 显示调试信息
if cmd == 'YOLO_start':
yolo_enabled = True
elif cmd == 'YOLO_stop':
yolo_enabled = False
elif cmd == 'change_model':
logger.debug("video_processing进程 模型已重新加载")
model = YOLO(cmd_01)
elif cmd == "change_conf":
logger.debug("更改置信度")
yolo_confidence = cmd_01
elif cmd == "change_class":
logger.debug(f"更改检测类别为: {cmd_01}")
target_class = cmd_01 # 更新目标类别
elif cmd == "aim_range_change":
aim_range = cmd_01
logger.debug(f"瞄准范围更改_01: {aim_range}")
# 等待新帧
frame_available_event.wait()
frame = shared_frame.copy()
frame_available_event.clear()
if yolo_enabled and model is not None:
# 执行 YOLO 推理并写入共享内存
processed_frame = YOLO_process_frame(
model, frame, yolo_confidence,
target_class=target_class, # 使用更新后的目标类别
box_shm_name=box_shm_name,
box_data_event=box_data_event,
box_lock=box_lock,
aim_range=aim_range,
)
else:
processed_frame = frame
# 将处理后的帧放入队列
processedVideo_queue.put(processed_frame)
except Exception as e:
logger.error(f"视频处理发生错误: {e}")
information_output_queue.put(("error_log", f"视频处理发生错误: {e}"))
finally:
existing_shm.close()
def YOLO_process_frame(model, frame, yolo_confidence=0.1, target_class="ALL",
box_shm_name=None, box_data_event=None, box_lock=None, aim_range=100):
"""对帧进行 YOLO 推理,返回带有标注的图像,并将最近的 Box 坐标、距离和唯一ID写入共享内存。"""
global unique_id_counter # 声明使用全局变量
try:
# logger.debug("收到的检测类别", target_class)
# 确定 YOLO 推理中要使用的类别
if target_class == "ALL":
classes = None # 允许检测所有类别
else:
try:
classes = [int(target_class)] # 只检测指定的类别
except ValueError:
classes = None # 如果转换失败,则检测所有类别
# logger.debug("实际检测类别:", classes)
# 执行 YOLO 推理
results = model.predict(
frame,
save=False,
device="cuda:0",
verbose=False,
save_txt=False,
half=True,
conf=yolo_confidence,
classes=classes # 指定类别
)
# 获取检测结果
boxes = results[0].boxes.xyxy # 获取所有 Box 的 xyxy 坐标
distances = [] # 用于存储每个 Box 到帧中心的距离
frame = results[0].plot() # 绘制检测框信息
# 计算帧中心点
frame_height, frame_width = frame.shape[:2]
frame_center = (frame_width / 2, frame_height / 2)
# 计算每个 Box 的距离
for box in boxes:
x1, y1, x2, y2 = box.cpu().numpy() # 获取每个 Box 的坐标
box_center = ((x1 + x2) / 2, (y1 + y2) / 2) # 计算每个 Box 的中心点
distance = sqrt((box_center[0] - frame_center[0]) **
2 + (box_center[1] - frame_center[1]) ** 2) # 计算距离
distances.append(distance) # 将距离加入到 distances 列表中
# 找到距离最近的 Box
if distances:
min_distance_idx = np.argmin(distances) # 找到最小距离的索引
closest_box = boxes[min_distance_idx].cpu().numpy()
closest_distance = distances[min_distance_idx]
else:
closest_box = None
closest_distance = None
# 将最近的 Box 坐标、距离和唯一ID写入共享内存
if box_shm_name and box_data_event and box_lock:
# 连接到共享内存
box_shm = shared_memory.SharedMemory(name=box_shm_name)
# 修改共享内存结构,加入unique_id
box_array = np.ndarray(
(1, 6), dtype=np.float32, buffer=box_shm.buf)
with box_lock:
box_array.fill(0) # 清空之前的数据
if closest_box is not None:
x1, y1, x2, y2 = closest_box
unique_id_counter += 1 # 递增唯一ID
unique_id = unique_id_counter
box_array[0, :4] = [x1, y1, x2, y2] # 存储最近的 Box 坐标
box_array[0, 4] = closest_distance # 存储距离
box_array[0, 5] = unique_id # 存储唯一ID
# 发送 Box 数据可用信号
box_data_event.set()
box_shm.close()
# 绘制一个淡蓝色的细圆(瞄准范围)
circle_color = (173, 216, 230) # 淡蓝色
cv2.circle(frame, (int(frame_center[0]), int(
frame_center[1])), aim_range, circle_color, 1)
# 绘制所有 Box
for i, box in enumerate(boxes):
x1, y1, x2, y2 = box.cpu().numpy()
box_center = (int((x1 + x2) / 2), int((y1 + y2) / 2))
# 默认所有框使用黄色连接线
box_color = (255, 255, 0) # 黄色边框
line_color = (255, 255, 0) # 黄色连接线
# 绘制矩形框
cv2.rectangle(frame, (int(x1), int(y1)),
(int(x2), int(y2)), box_color, 2)
# 绘制中心点
cv2.circle(frame, box_center, 5, (0, 0, 255), -1)
# 绘制连接线条
cv2.line(frame, box_center, (int(frame_center[0]), int(
frame_center[1])), line_color, 2)
# 计算距离
distance = sqrt(
(box_center[0] - frame_center[0]) ** 2 + (box_center[1] - frame_center[1]) ** 2)
# 绘制距离文本
distance_text = f"{distance:.1f}px"
cv2.putText(frame, distance_text, (int(x1), int(y1) - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
# 如果有最近的 Box,再绘制其绿色框和红色连接线(覆盖上一步绘制)
if closest_box is not None:
# 获取最近的 Box 的坐标和中心
x1, y1, x2, y2 = closest_box
box_center = (int((x1 + x2) / 2), int((y1 + y2) / 2))
# 只有当距离小于 aim_range 时,才绘制绿色框和红色连接线
if closest_distance < aim_range:
# 绘制最近的框的绿色边框
cv2.rectangle(frame, (int(x1), int(y1)),
(int(x2), int(y2)), (0, 255, 0), 3)
# 绘制中心点
cv2.circle(frame, box_center, 5, (0, 255, 0), -1)
# 绘制红色连接线
cv2.line(frame, box_center, (int(frame_center[0]), int(
frame_center[1])), (255, 0, 0), 3)
# 返回带有检测结果的图像
return frame # 返回绘制后的图像是 BGR 格式
except Exception as e:
logger.error(f"YOLO 推理失败: {e}")
return frame # 如果 YOLO 推理失败,返回原始帧
def mouse_move_prosses(box_shm_name, box_lock, mouseMoveProssesSignal_queue,
aim_speed_x=0.2, aim_speed_y=0.0, aim_range=100, offset_centerx=0, offset_centery=0.3,
lockKey=0x02, aimbot_switch=True, mouse_Side_Button_Witch=True,
screen_pixels_for_360_degrees=1800,
screen_height_pixels=900, near_speed_multiplier=2, slow_zone_radius=10, mouseMoveMode='win32'):
"""
鼠标移动进程,读取最近的 Box 数据并执行鼠标移动。
参数:
- box_shm_name: Box 坐标共享内存的名称
- box_lock: 用于同步访问共享内存的 Lock
- aim_speed_x: X轴基础瞄准速度
- aim_speed_y: Y轴基础瞄准速度
- aim_range: 瞄准范围
- threshold: 距离阈值
- fast_decay_rate: 当 distance < threshold 时的衰减率
- slow_decay_rate: 当 distance >= threshold 时的衰减率
- offset_centerx: X 轴瞄准偏移量
- offset_centery: Y 轴瞄准偏移量
- lockKey: 锁定键代码
- aimbot_switch: 自瞄开关
- mouse_Side_Button_Witch: 是否开启鼠标侧键瞄准
"""
IP = "192.168.2.188"
PORT = "1244"
MAC = "84FF7019"
connectKmBox = False
logger.debug("测试KmBoxNet连通性...")
response = subprocess.run(
["ping", IP], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = response.stdout.decode('gbk', errors='ignore')
logger.debug(output)
# 根据 returncode 判断是否连通
if response.returncode == 0:
logger.info("KmBoxNet IP连通成功")
else:
logger.error("KmBoxNet IP连通测试失败")
# 连接到 Box 共享内存
box_shm = shared_memory.SharedMemory(name=box_shm_name)
box_array = np.ndarray((1, 6), dtype=np.float32, buffer=box_shm.buf)
# 获取截图中心坐标
screenshot_center_x = 320 // 2
screenshot_center_y = 320 // 2
# 初始化变量
last_unique_id = 0 # 上次读取的数据的唯一ID
# 触发方式 按下/切换 press/toggle
trigger_mode = 'press'
trigger_toggle_state = False # 切换触发模式下的运行状态
prev_lockKey_pressed = False # 上一次循环时触发键的状态
# 初始化目标切换状态
target_switching = False
last_offset_distance = None # 上次的偏移后目标距离
fluctuation_range = 10 # 波动范围,单位:像素
jump_detection_switch = True # 跳变检测开关
try:
while True:
'''信号检查部分'''
if not mouseMoveProssesSignal_queue.empty():
command_data = mouseMoveProssesSignal_queue.get()
logger.debug(f"mouseMoveProssesSignal_queue 队列收到信号: {command_data}")
if isinstance(command_data, tuple):
cmd, cmd_01 = command_data
if cmd == "aimbot_switch_change":
aimbot_switch = cmd_01
logger.debug(f"自瞄状态更改: {aimbot_switch}")
elif cmd == "aim_speed_x_change":
aim_speed_x = cmd_01
logger.debug(f"X轴瞄准速度更改: {aim_speed_x}")
elif cmd == "aim_speed_y_change":
aim_speed_y = cmd_01
logger.debug(f"Y轴瞄准速度更改: {aim_speed_y}")
elif cmd == "aim_range_change":
aim_range = cmd_01
logger.debug(f"瞄准范围更改: {aim_range}")
elif cmd == "offset_centerx_change":
offset_centerx = cmd_01
logger.debug(f"瞄准偏移X更改: {offset_centerx}")
elif cmd == "offset_centery_change":
offset_centery = cmd_01
logger.debug(f"瞄准偏移Y更改: {offset_centery}")
elif cmd == "triggerMethod_change":
triggerMethod = cmd_01
logger.debug(f"瞄准热键触发方式更改: {triggerMethod}")
elif cmd == "lock_key_change":
lockKey = cmd_01
logger.debug(f"瞄准热键更改: {lockKey}")
elif cmd == "mouse_Side_Button_Witch_change":
mouse_Side_Button_Witch = cmd_01
logger.debug(f"侧键瞄准开关更改: {mouse_Side_Button_Witch}")
elif cmd == "trigger_mode_change":
trigger_mode = cmd_01 # 'press' 或 'toggle'
logger.debug(f"触发模式已更改为: {trigger_mode}")
elif cmd == "screen_pixels_for_360_degrees":
screen_pixels_for_360_degrees = cmd_01
logger.debug(f"游戏内X轴360度视角像素为: {screen_pixels_for_360_degrees}")
elif cmd == "screen_height_pixels":
screen_height_pixels = cmd_01
logger.debug(f"游戏内Y像素设置为: {screen_height_pixels}")
elif cmd == "near_speed_multiplier":
near_speed_multiplier = cmd_01
logger.debug(f"近点瞄准速度倍率设置为: {near_speed_multiplier}")
elif cmd == "slow_zone_radius":
slow_zone_radius = cmd_01
logger.debug(f"减速区域设置为: {slow_zone_radius}")
elif cmd == "mouseMoveMode":
mouseMoveMode = cmd_01
logger.debug(f"设置鼠标移动模式为: {mouseMoveMode}")
if mouseMoveMode == "KmBoxNet" and not connectKmBox:
'''连接KmBox'''
logger.info("尝试连接KmBox")
kmNet.init(IP, PORT, MAC) # 连接盒子
kmNet.enc_move(100, 100) # 测试移动
connectKmBox = True
logger.info("KmBox连接成功")
pixels_per_degree_x = screen_pixels_for_360_degrees / 360 # 每度需要的像素数度
pixels_per_degree_y = screen_height_pixels / 180 # 每度像素数
'''鼠标移动处理部分'''
# 获取最新的 Box 数据
with box_lock:
boxes = box_array.copy()
# 获取最近的 Box(第一项)
closest_box = boxes[0]
x1, y1, x2, y2, distance, unique_id = closest_box
# 检查是否有新数据
if unique_id != last_unique_id:
# 有新数据
last_unique_id = int(unique_id)
if not np.all(closest_box[:5] == 0):
# 计算Box的中心点
center_x = (x1 + x2) / 2
center_y = (y1 + y2) / 2
# 将 Box 中心点坐标从左上角坐标系转为以截图中心为原点的坐标系
center_x_relative_to_center = center_x - screenshot_center_x
center_y_relative_to_center = center_y - screenshot_center_y
# 计算中心点到上边框的垂直距离
vertical_distance = center_y - y1
# logger.debug(f"中心点到上边框的垂直距离: {vertical_distance}")
# 计算左边框到右边框的距离
horizontal_distance = x2 - x1
# logger.debug(f"左边框到右边框的水平距离: {horizontal_distance}")
# 计算目标相对于截图中心的偏移
delta_x = horizontal_distance * offset_centerx
delta_y = -vertical_distance * offset_centery
offset_target_x = center_x_relative_to_center + delta_x
offset_target_y = center_y_relative_to_center + delta_y
# logger.debug(f"移动距离处理前: {offset_target_x}, {offset_target_y}")
# 计算偏移后的距离
offset_distance = math.sqrt(
offset_target_x ** 2 + offset_target_y ** 2)
# 将像素偏移转换为角度偏移
angle_offset_x = offset_target_x / pixels_per_degree_x # 度
angle_offset_y = offset_target_y / pixels_per_degree_y # 度
# 基础 aim_speed 和最大 aim_speed
base_aim_speed_x = aim_speed_x # x轴的基础速度
base_aim_speed_y = aim_speed_y # y轴的基础速度
max_aim_speed_x = near_speed_multiplier * base_aim_speed_x # 最大X速度
max_aim_speed_y = near_speed_multiplier * base_aim_speed_y # 最大Y速度
# 动态调整 aim_speed
if offset_distance < slow_zone_radius:
# 偏移距离越小,aim_speed 越接近 base_aim_speed
last_aim_speed_x = base_aim_speed_x + (max_aim_speed_x - base_aim_speed_x) * (
offset_distance / slow_zone_radius)
last_aim_speed_y = base_aim_speed_y + (max_aim_speed_y - base_aim_speed_y) * (
offset_distance / slow_zone_radius)
elif offset_distance < aim_range:
# 使用偏移后的距离动态调整 aim_speed
last_aim_speed_x = base_aim_speed_x + (max_aim_speed_x - base_aim_speed_x) * (
1 - offset_distance / aim_range)
last_aim_speed_y = base_aim_speed_y + (max_aim_speed_y - base_aim_speed_y) * (
1 - offset_distance / aim_range)
else:
# 超过瞄准范围时,保持基础 aim_speed
last_aim_speed_x = base_aim_speed_x
last_aim_speed_y = base_aim_speed_y
# 保留小数点后两位
last_aim_speed_x = round(last_aim_speed_x, 2)
last_aim_speed_y = round(last_aim_speed_y, 2)
move_x = angle_offset_x * last_aim_speed_x * 2
move_y = angle_offset_y * last_aim_speed_y * 2
# 判断目标是否在瞄准范围内
target_is_within_range = distance < aim_range
if isinstance(lockKey, str) and lockKey.startswith("0x"):
lockKey = int(lockKey, 16) # 转换为十六进制整数
# 检查锁定键、鼠标侧键和 Shift 键是否按下
lockKey_pressed = bool(win32api.GetKeyState(lockKey) & 0x8000)
xbutton2_pressed = bool(win32api.GetKeyState(0x05) & 0x8000) # 鼠标侧键
shift_pressed = bool(win32api.GetKeyState(win32con.VK_SHIFT) & 0x8000) # Shift 键
if trigger_mode == 'press':
# 按下模式:只需检测按键是否被按下
should_move = aimbot_switch and target_is_within_range and (
lockKey_pressed or (
mouse_Side_Button_Witch and xbutton2_pressed)
)
elif trigger_mode == 'shift+press':
# Shift + 按下模式:需要同时按下 Shift 和锁定键
should_move = aimbot_switch and target_is_within_range and (
shift_pressed and lockKey_pressed
)
elif trigger_mode == 'toggle':
# 检测按键从未按下变为按下的瞬间
if lockKey_pressed and not prev_lockKey_pressed:
trigger_toggle_state = not trigger_toggle_state # 切换运行状态
# logger.debug(f"切换触发状态已更改为: {trigger_toggle_state}")
# 更新上一次的按键状态
prev_lockKey_pressed = lockKey_pressed
# 切换模式:运行状态由 `trigger_toggle_state` 控制
should_move = aimbot_switch and target_is_within_range and trigger_toggle_state
# 独立的触发逻辑:当仅按下 xbutton2_pressed,mouse_Side_Button_Witch 为 True,同时目标在瞄准范围内
if mouse_Side_Button_Witch and xbutton2_pressed and target_is_within_range:
should_move = True
# 判断是否发生目标切换:通过move_x_int和move_y_int的数值变化规律
if should_move:
move_x_int = round(move_x / 2)
move_y_int = round(move_y / 2)
if last_offset_distance is not None:
# 调用跳变检测函数
target_switching = jump_detection.check_target_switching(offset_distance, last_offset_distance,
jump_detection_switch, fluctuation_range, target_switching)
# 保存当前的 offset_distance 用于下一次比较
last_offset_distance = int(offset_distance)
# 目标切换时,拒绝执行移动
if not target_switching:
# print("执行移动")
if move_x_int != 0 or move_y_int != 0:
control.move(mouseMoveMode, move_x_int, move_y_int)
else:
# 当 should_move 为 False 时,重置last_offset_distance为 None,重置规律移动状态
# print("重置规律移动状态")
last_offset_distance = None
target_switching = False
except KeyboardInterrupt:
pass
finally:
box_shm.close()
class RookieAiAPP: # 主进程 (UI进程)
"""
RookieAiAPP
主进程中 初始化UI 进程。
"""
def __init__(self):
"""初始化 UI"""
self.information_output_queue = None
self.floating_information_signal_queue = None
self.video_queue = None
self.processedVideo_queue = None
self.YoloSignal_queue = None
self.videoSignal_queue = None
self.videoSignal_stop_queue = None
self.pipe_child = None
self.pipe_parent = None
self.app = QtWidgets.QApplication(sys.argv)
self.window = uic.loadUi(Root / "UI" / 'RookieAiWindow.ui') # 加载UI文件
self.window.setWindowTitle("YOLO识别系统") # 设置窗口名称
self.window.setWindowIcon(
QIcon("ico/ultralytics-botAvatarSrcUrl-1729379860806.png")) # 替换为图标文件路径
# self.window.resize(1290, 585) # 设置窗口的大小
self.window.setFixedSize(1290, 585) # 如果需要固定窗口大小,可以使用 setFixedSize
# 连接控制组件
self.window.OpVideoButton.clicked.connect(
self.toggle_video_button) # 连接按钮点击信号到打开视频信号的槽
# 连接 OpYoloButton 的点击信号到 toggle_YOLO_button 方法
self.window.OpYoloButton.clicked.connect(self.toggle_YOLO_button)
# 连接settingsButton按钮,显示设置按钮
self.window.settingsYoloButton.clicked.connect(self.show_settings)
self.window.closeYoloSettingsButton.clicked.connect(self.hide_settings)
# 连接保存按钮
self.window.saveButton.clicked.connect(self.save_settings)
# 连接窗口置顶复选框状态改变信号
self.window.topWindowCheckBox.stateChanged.connect(
self.update_window_on_top_state)
# 连接 解锁窗口大小 复选框状态改变信号
self.window.unlockWindowSizeCheckBox.stateChanged.connect(
self.update_unlock_window_size)
# 连接 跳变抑制 复选框改变信号
self.window.jumpSuppressionCheckBox.stateChanged.connect(
self.update_jum_suppression_state)
# 连接 resetSizeButton 的点击信号到槽函数
self.window.resetSizeButton.clicked.connect(self.reset_window_size)
# 连接模型选择按钮
self.window.chooseModelButton.clicked.connect(self.choose_model)
# 连接重启按钮
self.window.RestartButton.clicked.connect(self.restart_application)
# 连接 重新加载模型 按钮 change_yolo_model
self.window.reloadModelButton.clicked.connect(self.change_yolo_model)
# 连接 detectionTargetComboBox 的信号到槽函数
self.window.detectionTargetComboBox.currentTextChanged.connect(
self.on_detection_target_changed)
# 连接 aimBotCheckBox 的状态变化信号
self.window.aimBotCheckBox.stateChanged.connect(
self.on_aimBotCheckBox_state_changed)
# 连接 sideButtonCheckBox 的状态变化信号
self.window.sideButtonCheckBox.stateChanged.connect(
self.on_sideButtonCheckBox_state_changed)
# 连接 mobileModeQComboBox 的信号槽函数(鼠标移动模式)
self.window.mobileModeQComboBox.currentIndexChanged.connect(
self.on_mobileMode_changed)
# 连接 触发方式选择 conboBox
self.window.triggerMethodComboBox.currentTextChanged.connect(
self.on_trigger_method_changed)
# 连接 热键选择 HotkeyPushButton
self.window.HotkeyPushButton.clicked.connect(
lambda: self.on_trigger_hotkey_changed(self.window.HotkeyPushButton.text()))
self.window.announcement.setReadOnly(True)
# 设置公告内容
logger.debug("正在获取公告信息...")