返回列表 发布新帖

蚊子雷达追踪打击系统-源码

747 1
我是大哥 发表于 4 小时前 | 查看全部 阅读模式 <

马上注册,结交更多好友,享用更多功能,让你轻松玩转小K网。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
蚊子雷达追踪打击系统-源码
奇葩软件千千万,我的工具占一半

打包及程序介绍见原创发布区

蚊子雷达追踪打击系统-源码

蚊子雷达追踪打击系统-源码

  1. import cv2
  2. import numpy as np
  3. import matplotlib
  4. import math
  5. from matplotlib import pyplot as plt
  6. from matplotlib import rcParams
  7. from matplotlib.animation import FuncAnimation
  8. from collections import deque
  9. from datetime import datetime
  10. import time
  11. import pygame
  12. import os
  13. import wave
  14. import struct

  15. # **添加以下两行设置后端**
  16. matplotlib.use('Qt5Agg')  # 替换原有的'TkAgg'

  17. # 在独立线程中运行Matplotlib动画
  18. import threading

  19. # 设置中文字体
  20. rcParams['font.family'] = 'SimHei'
  21. rcParams['axes.unicode_minus'] = False


  22. # 生成驱蚊音频文件
  23. def generate_anti_mosquito_sound():
  24.     sample_rate = 44100  # 采样率:每秒采集44100个音频样本
  25.     duration = 3.0  # 音频时长:3秒
  26.     freq = 22000  # 频率:22000Hz(超声波,接近蚊子能感知的上限)

  27.     samples = []
  28.     for i in range(int(duration * sample_rate)):
  29.         sample = 0.5 * math.sin(2 * math.pi * freq * i / sample_rate)
  30.         samples.append(sample)

  31.     filename = "mosquito_sound.wav"
  32.     with wave.open(filename, 'w') as wf:
  33.         wf.setnchannels(1)
  34.         wf.setsampwidth(2)
  35.         wf.setframerate(sample_rate)
  36.         for sample in samples:
  37.             data = struct.pack('<h', int(sample * 32767))
  38.             wf.writeframesraw(data)
  39.     return filename


  40. # 初始化音频系统
  41. try:
  42.     pygame.mixer.init()
  43.     sound_file = generate_anti_mosquito_sound()
  44.     mosquito_sound = pygame.mixer.Sound(sound_file)
  45.     print("已生成驱蚊音频文件")
  46. except Exception as e:
  47.     print(f"音频初始化失败: {e}")
  48.     mosquito_sound = None

  49. # 初始化雷达图
  50. plt.style.use('dark_background')
  51. fig = plt.figure(figsize=(10, 8), facecolor='black')
  52. fig.suptitle('蚊子雷达追踪打击系统', color='lime', fontsize=16, fontweight='bold')

  53. # 创建雷达主界面 - 改进的潜水艇风格
  54. ax_radar = fig.add_subplot(121, polar=True, facecolor=(0, 0.05, 0))
  55. ax_info = fig.add_subplot(122, facecolor='black')
  56. ax_info.axis('off')

  57. # 雷达图美化设置 - 军用风格
  58. ax_radar.set_theta_zero_location('N')
  59. ax_radar.set_theta_direction(-1)
  60. ax_radar.set_ylim(0, 500)
  61. ax_radar.set_yticklabels([])
  62. ax_radar.grid(color='lime', alpha=0.2, linestyle='-')
  63. ax_radar.spines['polar'].set_visible(False)
  64. ax_radar.tick_params(axis='both', colors='lime')

  65. # 添加雷达背景效果 - 同心圆网格
  66. background_circles = []
  67. for r in [100, 200, 300, 400, 500]:
  68.     circle = plt.Circle((0, 0), r, transform=ax_radar.transData._b,
  69.                         fill=False, color='lime', alpha=0.1, linewidth=0.5)
  70.     ax_radar.add_artist(circle)
  71.     background_circles.append(circle)
  72.     ax_radar.text(0, r, f'{r}cm', color='lime', ha='center', va='center',
  73.                   fontsize=8, alpha=0.7)

  74. # 添加雷达中心点
  75. center_point = ax_radar.scatter([0], [0], c='lime', s=50, alpha=0.8)

  76. # 初始化雷达元素
  77. scan_line = ax_radar.plot([], [], color='lime', linestyle='-', linewidth=2, alpha=0.9)[0]
  78. scan_shadow = ax_radar.plot([], [], color='lime', linestyle='-', linewidth=8, alpha=0.1)[0]
  79. mosquito_dots = ax_radar.scatter([], [], c='red', s=80, alpha=0.9,
  80.                                  edgecolors='yellow', linewidths=1.5, zorder=10)
  81. scan_arc = None
  82. scan_arc_fill = None
  83. trail_lines = []

  84. # 初始化雷达数据
  85. max_distance = 500
  86. r = deque([0] * 360, maxlen=360)
  87. theta = np.linspace(0, 2 * np.pi, 360, endpoint=False)


  88. # 系统状态变量
  89. class SystemState:
  90.     def __init__(self):
  91.         self.auto_sound = True  # 默认开启声波攻击
  92.         self.sound_playing = False
  93.         self.last_sound_time = 0
  94.         self.total_detected = 0
  95.         self.detected_today = 0
  96.         self.start_time = datetime.now()
  97.         self.screenshot_count = 0


  98. system_state = SystemState()


  99. # 初始化信息面板
  100. def init_info_panel():
  101.     titles = ["系统状态", "检测统计", "蚊子信息", "追踪数据", "声波设置"]
  102.     contents = [
  103.         [f"状态: 运行中", f"扫描中", f"摄像头: 开启", f"启动: {system_state.start_time.strftime('%H:%M:%S')}"],
  104.         [f"当前: 0", f"今日: 0", f"最大: 0", f"平均: 0"],
  105.         [f"速度: 0 cm/s", f"大小: 0 px", f"方向: -", f"距离: 0 cm"],
  106.         [f"追踪: 0", f"历史: 0", f"误报: 0", f"准确率: 0%"],
  107.         [f"声波驱蚊: 开启", f"按A键切换", f"截图: 按P键", ""]  # 修改显示文本
  108.     ]

  109.     title_y_positions = [0.92, 0.72, 0.52, 0.32, 0.12]
  110.     content_line_height = 0.05
  111.     title_content_gap = 0.02

  112.     info_texts = []
  113.     for i, (title, content) in enumerate(zip(titles, contents)):
  114.         ax_info.text(0.1, title_y_positions[i], title,
  115.                      color='cyan', fontsize=11, fontweight='bold',
  116.                      transform=ax_info.transAxes)

  117.         for j, item in enumerate(content):
  118.             text = ax_info.text(0.15,
  119.                                 title_y_positions[i] - title_content_gap - j * content_line_height,
  120.                                 item,
  121.                                 color='lime', fontsize=9,
  122.                                 transform=ax_info.transAxes)
  123.             info_texts.append(text)

  124.     ax_info.text(0.5, 0.02, "By:Killerzeno", color='white', ha='center',
  125.                  fontsize=14, fontweight='bold', style='italic',
  126.                  transform=ax_info.transAxes)
  127.     return info_texts


  128. info_texts = init_info_panel()

  129. # 初始化摄像头
  130. cap = cv2.VideoCapture(0)
  131. cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
  132. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

  133. # 边缘检测参数(可调整)
  134. EDGE_THRESHOLD1 = 50  # Canny边缘检测低阈值
  135. EDGE_THRESHOLD2 = 150  # Canny边缘检测高阈值

  136. # 背景减法器用于运动检测
  137. fgbg = cv2.createBackgroundSubtractorMOG2(history=100, varThreshold=16, detectShadows=False)

  138. # 用于扫描动画的变量
  139. current_angle = 0
  140. scan_speed = 5
  141. mosquito_count = 0
  142. max_mosquito_count = 0
  143. false_positives = 0
  144. true_positives = 0


  145. # 蚊子轨迹类
  146. class MosquitoTrack:
  147.     def __init__(self, id, x, y, time):
  148.         self.id = id
  149.         self.positions = [(x, y, time)]
  150.         self.speeds = []
  151.         self.directions = []
  152.         self.last_update = time
  153.         self.active = True

  154.     def update(self, x, y, time):
  155.         dx = x - self.positions[-1][0]
  156.         dy = y - self.positions[-1][1]
  157.         dt = time - self.last_update
  158.         if dt > 0:
  159.             speed = np.sqrt(dx ** 2 + dy ** 2) / dt
  160.             direction = np.degrees(np.arctan2(dy, dx))
  161.             self.speeds.append(speed)
  162.             self.directions.append(direction)

  163.         self.positions.append((x, y, time))
  164.         self.last_update = time
  165.         self.active = True

  166.     def get_current_speed(self):
  167.         return np.mean(self.speeds[-3:]) if len(self.speeds) > 0 else 0

  168.     def get_current_direction(self):
  169.         if len(self.directions) > 0:
  170.             return self.directions[-1]
  171.         return None


  172. tracks = []
  173. next_id = 1


  174. def play_anti_mosquito_sound():
  175.     if system_state.auto_sound and mosquito_sound:
  176.         current_time = time.time()
  177.         if current_time - system_state.last_sound_time > 5:
  178.             try:
  179.                 mosquito_sound.play()
  180.                 system_state.last_sound_time = current_time
  181.                 system_state.sound_playing = True
  182.             except Exception as e:
  183.                 print(f"播放音频失败: {e}")


  184. def take_screenshot():
  185.     screenshot_dir = "screenshots"
  186.     if not os.path.exists(screenshot_dir):
  187.         os.makedirs(screenshot_dir)
  188.     timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  189.     filename = f"{screenshot_dir}/screenshot_{system_state.screenshot_count}_{timestamp}.png"
  190.     plt.savefig(filename)
  191.     system_state.screenshot_count += 1
  192.     print(f"截图已保存: {filename}")


  193. def update_radar(frame):
  194.     global current_angle, r, mosquito_count, max_mosquito_count
  195.     global false_positives, true_positives, tracks, next_id
  196.     global scan_arc, scan_arc_fill, trail_lines

  197.     current_time = time.time()

  198.     # 转换为灰度图像
  199.     gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

  200.     # 应用背景减法检测运动
  201.     fgmask = fgbg.apply(gray)

  202.     # 形态学操作
  203.     kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
  204.     fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
  205.     fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel)

  206.     # 寻找轮廓
  207.     contours, _ = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

  208.     # 检测到的蚊子位置
  209.     current_detections = []
  210.     mosquito_info = []

  211.     for contour in contours:
  212.         area = cv2.contourArea(contour)
  213.         perimeter = cv2.arcLength(contour, True)

  214.         if 5 < area < 150 and perimeter > 10:
  215.             (x, y), radius = cv2.minEnclosingCircle(contour)
  216.             if 2 < radius < 20:
  217.                 circularity = 4 * np.pi * area / (perimeter ** 2) if perimeter > 0 else 0

  218.                 if circularity > 0.5:
  219.                     center_x = x - frame.shape[1] // 2
  220.                     center_y = y - frame.shape[0] // 2

  221.                     angle = np.arctan2(center_y, center_x) % (2 * np.pi)
  222.                     distance = np.sqrt(center_x ** 2 + center_y ** 2)
  223.                     distance = min(distance, max_distance)

  224.                     current_detections.append((x, y, angle, distance, area, radius))

  225.     # 多目标跟踪
  226.     active_tracks = [t for t in tracks if t.active]
  227.     matched = [False] * len(current_detections)

  228.     for track in active_tracks:
  229.         min_dist = float('inf')
  230.         best_match = None

  231.         for i, (x, y, _, _, _, _) in enumerate(current_detections):
  232.             if not matched[i]:
  233.                 last_x, last_y, _ = track.positions[-1]
  234.                 dist = np.sqrt((x - last_x) ** 2 + (y - last_y) ** 2)

  235.                 if dist < 50 and dist < min_dist:
  236.                     min_dist = dist
  237.                     best_match = i

  238.         if best_match is not None:
  239.             x, y, angle, distance, area, radius = current_detections[best_match]
  240.             track.update(x, y, current_time)
  241.             matched[best_match] = True
  242.             mosquito_info.append((angle, distance, track))
  243.             true_positives += 1
  244.         else:
  245.             false_positives += 1

  246.     # 创建新轨迹
  247.     for i, (x, y, angle, distance, area, radius) in enumerate(current_detections):
  248.         if not matched[i]:
  249.             new_track = MosquitoTrack(next_id, x, y, current_time)
  250.             tracks.append(new_track)
  251.             mosquito_info.append((angle, distance, new_track))
  252.             next_id += 1
  253.             system_state.total_detected += 1
  254.             system_state.detected_today += 1

  255.     # 标记不活跃的轨迹
  256.     for track in active_tracks:
  257.         if current_time - track.last_update > 0.5:
  258.             track.active = False

  259.     # 更新雷达数据
  260.     mosquito_count = len([t for t in tracks if t.active])
  261.     max_mosquito_count = max(max_mosquito_count, mosquito_count)

  262.     # 播放驱蚊声
  263.     if mosquito_count > 0:
  264.         play_anti_mosquito_sound()

  265.     # 更新扫描线效果
  266.     current_angle = (current_angle + scan_speed * 2) % 360  # 加快扫描速度
  267.     scan_rad = np.radians(current_angle)

  268.     # 主扫描线
  269.     scan_line.set_data([scan_rad, scan_rad], [0, max_distance])

  270.     # 扫描线尾迹
  271.     trail_length = 30
  272.     trail_angles = np.linspace(scan_rad - np.radians(trail_length), scan_rad, 10)
  273.     scan_shadow.set_data(trail_angles, [max_distance] * 10)

  274.     # 更新扇形扫描区域
  275.     if scan_arc is not None:
  276.         scan_arc.remove()
  277.     if scan_arc_fill is not None:
  278.         scan_arc_fill.remove()

  279.     scan_width = 30
  280.     scan_start = np.radians(current_angle - scan_width) % (2 * np.pi)
  281.     scan_end = np.radians(current_angle + scan_width) % (2 * np.pi)

  282.     # 扇形边框
  283.     scan_theta = np.linspace(scan_start, scan_end, 50)
  284.     scan_arc = ax_radar.plot(scan_theta, [max_distance] * 50,
  285.                              color='lime', alpha=0.5, linewidth=1)[0]

  286.     # 扇形填充(渐变效果)
  287.     scan_r = np.linspace(0, max_distance, 50)
  288.     scan_theta, scan_r = np.meshgrid(scan_theta, scan_r)
  289.     scan_theta = scan_theta.flatten()
  290.     scan_r = scan_r.flatten()

  291.     angle_diff = np.abs((np.degrees(scan_theta) - current_angle + 180) % 360 - 180)
  292.     alphas = np.where(angle_diff < scan_width, 1 - angle_diff / scan_width, 0)
  293.     colors = np.zeros((len(scan_theta), 4))
  294.     colors[:, 1] = 1.0
  295.     colors[:, 3] = alphas * 0.1

  296.     scan_arc_fill = ax_radar.scatter(scan_theta, scan_r, c=colors, s=2,
  297.                                      edgecolors='none', zorder=0)

  298.     # 更新蚊子标记
  299.     if mosquito_info:
  300.         angles, distances, tracks_info = zip(*mosquito_info)
  301.         sizes = [50 + 30 * math.sin(time.time() * 10)] * len(angles)  # 脉冲效果
  302.         colors = ['red' if t.active else 'orange' for t in tracks_info]
  303.         mosquito_dots.set_offsets(np.column_stack([angles, distances]))
  304.         mosquito_dots.set_sizes(sizes)
  305.         mosquito_dots.set_color(colors)
  306.     else:
  307.         mosquito_dots.set_offsets(np.empty((0, 2)))

  308.     # 更新轨迹线
  309.     for line in trail_lines:
  310.         line.remove()
  311.     trail_lines = []

  312.     if mosquito_info:
  313.         for angle, distance, track in mosquito_info:
  314.             if len(track.positions) > 1:
  315.                 # 主轨迹线
  316.                 history_angles = []
  317.                 history_distances = []
  318.                 for i in range(max(0, len(track.positions) - 5), len(track.positions)):
  319.                     x, y, _ = track.positions[i]
  320.                     center_x = x - frame.shape[1] // 2
  321.                     center_y = y - frame.shape[0] // 2
  322.                     angle = np.arctan2(center_y, center_x) % (2 * np.pi)
  323.                     distance = np.sqrt(center_x ** 2 + center_y ** 2)
  324.                     history_angles.append(angle)
  325.                     history_distances.append(distance)

  326.                 if len(history_angles) > 1:
  327.                     # 主轨迹线
  328.                     main_line = ax_radar.plot(history_angles, history_distances,
  329.                                               color='cyan', alpha=0.7,
  330.                                               linewidth=1.5, zorder=5)[0]
  331.                     trail_lines.append(main_line)

  332.                     # 轨迹尾迹
  333.                     trail_alpha = 0.3
  334.                     for i in range(1, 4):
  335.                         if len(history_angles) > i:
  336.                             trail_line = ax_radar.plot(
  337.                                 history_angles[-i - 1:-i],
  338.                                 history_distances[-i - 1:-i],
  339.                                 color='white', alpha=trail_alpha,
  340.                                 linewidth=2 + i, zorder=4 - i)[0]
  341.                             trail_lines.append(trail_line)
  342.                             trail_alpha *= 0.7

  343.     # 更新信息面板
  344.     accuracy = true_positives / (true_positives + false_positives) * 100 if (
  345.                                                                                     true_positives + false_positives) > 0 else 0

  346.     info_texts[0].set_text(f"状态: 运行中")
  347.     info_texts[1].set_text(f"扫描中")
  348.     info_texts[2].set_text(f"摄像头: 开启")
  349.     info_texts[3].set_text(f"启动: {system_state.start_time.strftime('%H:%M:%S')}")

  350.     info_texts[4].set_text(f"当前: {mosquito_count}")
  351.     info_texts[5].set_text(f"今日: {system_state.detected_today}")
  352.     info_texts[6].set_text(f"最大: {max_mosquito_count}")
  353.     info_texts[7].set_text(
  354.         f"平均: {system_state.total_detected / ((time.time() - system_state.start_time.timestamp()) / 3600):.1f}/h")

  355.     if mosquito_info:
  356.         _, _, track = mosquito_info[0]
  357.         speed = track.get_current_speed()
  358.         direction = track.get_current_direction()
  359.         dir_text = f"{direction:.1f}°" if direction is not None else "-"

  360.         info_texts[8].set_text(f"速度: {speed:.1f} px/s")
  361.         info_texts[9].set_text(f"大小: {track.positions[-1][2]:.1f} px")
  362.         info_texts[10].set_text(f"方向: {dir_text}")
  363.         info_texts[11].set_text(f"距离: {distance:.1f} cm")
  364.     else:
  365.         info_texts[8].set_text(f"速度: 0 px/s")
  366.         info_texts[9].set_text(f"大小: 0 px")
  367.         info_texts[10].set_text(f"方向: -")
  368.         info_texts[11].set_text(f"距离: 0 cm")

  369.     info_texts[12].set_text(f"追踪: {len(tracks)}")
  370.     info_texts[13].set_text(f"历史: {system_state.total_detected}")
  371.     info_texts[14].set_text(f"误报: {false_positives}")
  372.     info_texts[15].set_text(f"准确率: {accuracy:.1f}%")

  373.     sound_status = "开启" if system_state.auto_sound else "关闭"
  374.     playing_status = "(播放中)" if system_state.sound_playing else ""
  375.     info_texts[16].set_text(f"声波驱蚊: {sound_status} {playing_status}")
  376.     info_texts[17].set_text(f"按A键切换")
  377.     info_texts[18].set_text(f"截图: 按P键")

  378.     return [scan_line, scan_shadow, mosquito_dots, scan_arc, scan_arc_fill,
  379.             *trail_lines, *info_texts]


  380. # 创建动画
  381. def update(frame):
  382.     ret, frame = cap.read()
  383.     if not ret:
  384.         return []

  385.     frame = cv2.flip(frame, 1)

  386.     # 灰度处理与边缘检测
  387.     gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  388.     blurred = cv2.GaussianBlur(gray_frame, (5, 5), 0)
  389.     edges = cv2.Canny(blurred, EDGE_THRESHOLD1, EDGE_THRESHOLD2)

  390.     # 寻找轮廓
  391.     contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

  392.     # 创建空白图像用于绘制轮廓
  393.     edge_display = np.zeros_like(frame)
  394.     cv2.drawContours(edge_display, contours, -1, (0, 255, 0), 1)

  395.     artists = update_radar(frame)

  396.     # 显示窗口
  397.     cv2.imshow('Mosquito Tracking', cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
  398.     cv2.imshow('Edges', edge_display)  # 显示轮廓绘制结果

  399.     key = cv2.waitKey(1)
  400.     if key & 0xFF == ord('q'):
  401.         ani.event_source.stop()
  402.         cap.release()
  403.         cv2.destroyAllWindows()
  404.         plt.close('all')
  405.         return []
  406.     elif key & 0xFF == ord('a'):
  407.         system_state.auto_sound = not system_state.auto_sound
  408.     elif key & 0xFF == ord('p'):
  409.         take_screenshot()

  410.     if system_state.sound_playing and not pygame.mixer.get_busy():
  411.         system_state.sound_playing = False

  412.     return artists


  413. # 开始动画
  414. try:
  415.     # 启动时自动播放一次声波
  416.     if system_state.auto_sound and mosquito_sound:
  417.         mosquito_sound.play()
  418.         system_state.sound_playing = True
  419.         system_state.last_sound_time = time.time()

  420.     ani = FuncAnimation(fig, update, frames=None, interval=30, blit=True, cache_frame_data=False)
  421.     plt.tight_layout()
  422.     plt.show()
  423. except Exception as e:
  424.     print(f"程序错误: {e}")
  425. finally:
  426.     if 'cap' in locals() and cap.isOpened():
  427.         cap.release()
  428.     cv2.destroyAllWindows()
  429.     plt.close('all')
复制代码



评论1

总裁Lv.3 发表于 1 小时前 来自手机 | 查看全部 <
牛而逼之
回复

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表