激光追踪打蚊器模拟
把视觉追踪打蚊器的思路搬到浏览器:Canvas 模拟监控画面、瞄准、激光发射,并附 OpenCV 真实硬件版代码。
命中 0 / 发射 0
移动鼠标瞄准,点击发射激光打蚊子;下方代码为视觉追踪思路。
代码示例:视觉追踪打蚊器思路
py
# Python + OpenCV:运动目标检测(真实硬件版核心)
import cv2
import numpy as np
cap = cv2.VideoCapture(0) # 摄像头
fgbg = cv2.createBackgroundSubtractorMOG2() # 背景建模
while True:
ret, frame = cap.read()
if not ret:
break
mask = fgbg.apply(frame) # 前景掩码
mask = cv2.erode(mask, None, iterations=1)
mask = cv2.dilate(mask, None, iterations=2)
cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
target = None
for c in cnts:
area = cv2.contourArea(c)
if area < 200: # 过滤小噪点
continue
(x, y, w, h) = cv2.boundingRect(c)
if target is None or w * h > target[4]:
target = (x + w // 2, y + h // 2, w, h, w * h)
if target is not None:
cx, cy = target[0], target[1]
cv2.circle(frame, (cx, cy), 8, (0, 0, 255), 2)
# 将像素坐标映射为舵机角度,控制云台转向
pan = int(np.interp(cx, [0, frame.shape[1]], [0, 180]))
tilt = int(np.interp(cy, [0, frame.shape[0]], [90, 0]))
# send_to_servo(pan, tilt)
cv2.imshow("tracking", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
操作步骤
- 上方 Demo 可玩:移动瞄准、点击发射激光,命中蚊子计分。
- 真实硬件思路:摄像头帧差检测运动目标 → 追踪坐标 → 舵机云台带动激光器。
- 安全提醒:激光功率必须低于安全标准,仅用于展示,请勿照射人眼。
来源参考
GitHub 关键词:laser-mosquito-killer、opencv-object-tracking、pan-tilt-laser。