yolo
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,50 @@
|
||||
# test_audio.pyx
|
||||
from maix import audio, time, app, gpio
|
||||
|
||||
def run_player_loop():
|
||||
"""
|
||||
播放控制主循环函数
|
||||
"""
|
||||
# 初始化音频播放器
|
||||
p = audio.Player("/root/gun.wav")
|
||||
p.volume(40)
|
||||
|
||||
# 初始化 GPIO 引脚为输出
|
||||
led = gpio.GPIO("A25", gpio.Mode.OUT)
|
||||
# 设置低电平
|
||||
led.value(0)
|
||||
|
||||
# 主循环
|
||||
while not app.need_exit():
|
||||
led.value(1) # 点亮 LED
|
||||
time.sleep_ms(200) # 保持 200ms
|
||||
led.value(0) # 熄灭 LED
|
||||
p.play() # 播放音频
|
||||
time.sleep_ms(1000) # 等待 1 秒
|
||||
|
||||
print("play finish!")
|
||||
|
||||
|
||||
# 可选:添加一个简单的测试函数
|
||||
def hello():
|
||||
return "Hello from test_audio!"
|
||||
|
||||
|
||||
# 可选:添加一个初始化函数
|
||||
def init_led():
|
||||
"""单独测试 GPIO"""
|
||||
led = gpio.GPIO("A25", gpio.Mode.OUT)
|
||||
led.value(0)
|
||||
return "LED initialized"
|
||||
|
||||
|
||||
# 可选:添加一个播放测试函数
|
||||
def test_play():
|
||||
"""单独测试音频播放"""
|
||||
p = audio.Player("/root/gun.wav")
|
||||
p.volume(50)
|
||||
p.play()
|
||||
return "Playing..."
|
||||
|
||||
|
||||
run_player_loop()
|
||||
@@ -0,0 +1,25 @@
|
||||
from maix import audio, time, app,gpio
|
||||
|
||||
|
||||
# button1 = gpio.GPIO("ADC", gpio.Mode.IN)
|
||||
button3 = gpio.GPIO("A26", gpio.Mode.IN) # 可用
|
||||
button2 = gpio.GPIO("A16", gpio.Mode.IN)
|
||||
#设置低电平
|
||||
from maix.peripheral import adc
|
||||
channel = 0
|
||||
res_bit = adc.RES_BIT_12
|
||||
_adc_obj = adc.ADC(channel, res_bit)
|
||||
|
||||
|
||||
while not app.need_exit():
|
||||
# print(f"b1: {button1.value()}")
|
||||
|
||||
print(f"b2: {button2.value()}")
|
||||
|
||||
# print(_adc_obj.read_vol())
|
||||
print(f"b3: {button3.value()}")
|
||||
time.sleep_ms(50)
|
||||
|
||||
# time.sleep_ms(1000)
|
||||
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# from maix import time, rtsp, camera, image
|
||||
|
||||
# # 1. 初始化摄像头(注意:RTSP需要NV21格式)
|
||||
# # 分辨率可以根据需要调整,如 640x480 或 1280x720
|
||||
# cam = camera.Camera(640, 480, image.Format.FMT_YVU420SP)
|
||||
|
||||
# # 2. 创建并启动RTSP服务器
|
||||
# server = rtsp.Rtsp()
|
||||
# server.bind_camera(cam)
|
||||
# server.start()
|
||||
|
||||
# # 3. 打印出访问地址,例如: rtsp://192.168.xxx.xxx:8554/live
|
||||
# print("RTSP 流地址:", server.get_url())
|
||||
|
||||
# # 4. 保持服务运行
|
||||
# while True:
|
||||
# time.sleep(1)
|
||||
|
||||
|
||||
|
||||
from maix import camera, time, app, http, image
|
||||
|
||||
# 初始化相机,注意格式要用 FMT_RGB888(JPEG 编码需要 RGB 输入)
|
||||
cam = camera.Camera(640, 480, image.Format.FMT_RGB888)
|
||||
|
||||
# 创建 JPEG 流服务器
|
||||
stream = http.JpegStreamer()
|
||||
stream.start()
|
||||
|
||||
print("RTSP 替代方案 - HTTP JPEG 流地址: http://{}:{}".format(stream.host(), stream.port()))
|
||||
print("请在浏览器或 OpenCV 中访问: http://<MaixCAM_IP>:8000/stream")
|
||||
|
||||
while not app.need_exit():
|
||||
img = cam.read()
|
||||
jpg = img.to_jpeg() # 将 RGB 图像编码为 JPEG
|
||||
stream.write(jpg) # 推送到 HTTP 客户端
|
||||
@@ -0,0 +1,20 @@
|
||||
# test_camera.py
|
||||
from maix import camera, display, time
|
||||
|
||||
try:
|
||||
print("Initializing camera...")
|
||||
cam = camera.Camera(640,480)
|
||||
# cam = camera.Camera(1280,720)
|
||||
# cam.get_exposure_us()
|
||||
# print("Camera exposure: ", cam.get_exposure_us())
|
||||
print("Camera initialized successfully!")
|
||||
|
||||
disp = display.Display()
|
||||
|
||||
while True:
|
||||
frame = cam.read()
|
||||
disp.show(frame)
|
||||
time.sleep_ms(50)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
@@ -0,0 +1,144 @@
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
class _StopMonitor(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class _FakeTime:
|
||||
now_ms = 0
|
||||
stop_at_ms = None
|
||||
|
||||
@classmethod
|
||||
def reset(cls, stop_at_ms=None):
|
||||
cls.now_ms = 0
|
||||
cls.stop_at_ms = stop_at_ms
|
||||
|
||||
@classmethod
|
||||
def ticks_ms(cls):
|
||||
return cls.now_ms
|
||||
|
||||
@classmethod
|
||||
def sleep_ms(cls, milliseconds):
|
||||
cls.now_ms += milliseconds
|
||||
if cls.stop_at_ms is not None and cls.now_ms >= cls.stop_at_ms:
|
||||
raise _StopMonitor()
|
||||
|
||||
|
||||
def _load_power_module():
|
||||
module_path = Path(__file__).resolve().parents[1] / "power.py"
|
||||
module_name = "power_charging_shutdown_test"
|
||||
maix_module = types.ModuleType("maix")
|
||||
maix_module.time = _FakeTime
|
||||
|
||||
previous_maix = sys.modules.get("maix")
|
||||
sys.modules["maix"] = maix_module
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(module_name, module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
finally:
|
||||
if previous_maix is None:
|
||||
sys.modules.pop("maix", None)
|
||||
else:
|
||||
sys.modules["maix"] = previous_maix
|
||||
|
||||
|
||||
power = _load_power_module()
|
||||
|
||||
|
||||
class ChargingShutdownTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.config_patch = mock.patch.multiple(
|
||||
power.config,
|
||||
CHARGING_SHUTDOWN_ENABLED=True,
|
||||
CHARGING_DIAGNOSTIC_LOG_ENABLED=False,
|
||||
CHARGING_CHECK_INTERVAL_MS=5000,
|
||||
CHARGING_CURRENT_THRESHOLD_MA=100.0,
|
||||
CHARGING_CONFIRM_COUNT=2,
|
||||
CHARGING_NOTIFY_TIMEOUT_MS=30000,
|
||||
CHARGING_EXIT_SCRIPT="/tmp/charging_exit.sh",
|
||||
)
|
||||
self.config_patch.start()
|
||||
self.network_manager = mock.Mock()
|
||||
self.network_manager.safe_enqueue_and_wait.return_value = True
|
||||
network_module = types.ModuleType("network")
|
||||
network_module.network_manager = self.network_manager
|
||||
self.network_module_patch = mock.patch.dict(
|
||||
sys.modules,
|
||||
{"network": network_module},
|
||||
)
|
||||
self.network_module_patch.start()
|
||||
_FakeTime.reset()
|
||||
|
||||
def tearDown(self):
|
||||
self.network_module_patch.stop()
|
||||
self.config_patch.stop()
|
||||
|
||||
def test_two_charging_samples_notify_server_and_exit(self):
|
||||
popen_calls = []
|
||||
with (
|
||||
mock.patch.object(power, "get_current", return_value=-200.0),
|
||||
mock.patch.object(power.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(
|
||||
power.subprocess,
|
||||
"Popen",
|
||||
side_effect=lambda args: popen_calls.append(args),
|
||||
),
|
||||
):
|
||||
power.charging_shutdown_monitor()
|
||||
|
||||
self.assertEqual(_FakeTime.now_ms, 5000)
|
||||
self.assertEqual(len(popen_calls), 1)
|
||||
self.network_manager.safe_enqueue_and_wait.assert_called_once_with(
|
||||
{"poweroff": "充电中"}, 2, high=True, timeout_ms=30000
|
||||
)
|
||||
|
||||
def test_discharging_does_not_notify_or_exit(self):
|
||||
_FakeTime.reset(stop_at_ms=10000)
|
||||
popen_calls = []
|
||||
|
||||
with (
|
||||
mock.patch.object(power, "get_current", return_value=200.0),
|
||||
mock.patch.object(power.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(
|
||||
power.subprocess,
|
||||
"Popen",
|
||||
side_effect=lambda args: popen_calls.append(args),
|
||||
),
|
||||
self.assertRaises(_StopMonitor),
|
||||
):
|
||||
power.charging_shutdown_monitor()
|
||||
|
||||
self.assertEqual(popen_calls, [])
|
||||
self.network_manager.safe_enqueue_and_wait.assert_not_called()
|
||||
|
||||
def test_failed_sample_resets_confirmation_count(self):
|
||||
popen_calls = []
|
||||
currents = iter((-200.0, 0.0, -200.0, -200.0))
|
||||
with (
|
||||
mock.patch.object(power, "get_current", side_effect=lambda: next(currents)),
|
||||
mock.patch.object(power.os.path, "isfile", return_value=True),
|
||||
mock.patch.object(
|
||||
power.subprocess,
|
||||
"Popen",
|
||||
side_effect=lambda args: popen_calls.append(args),
|
||||
),
|
||||
):
|
||||
power.charging_shutdown_monitor()
|
||||
|
||||
self.assertEqual(_FakeTime.now_ms, 15000)
|
||||
self.assertEqual(len(popen_calls), 1)
|
||||
self.network_manager.safe_enqueue_and_wait.assert_called_once_with(
|
||||
{"poweroff": "充电中"}, 2, high=True, timeout_ms=30000
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,330 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
离线测试脚本:直接复用 detect_circle 逻辑进行测试
|
||||
运行环境:MaixPy (Sipeed MAIX)
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
# import time
|
||||
from maix import image, time
|
||||
import cv2
|
||||
import numpy as np
|
||||
import math
|
||||
|
||||
# ==================== 全局配置 (与 test_main.py 保持一致) ====================
|
||||
REAL_RADIUS_CM = 20 # 靶心实际半径(厘米)
|
||||
|
||||
def detect_circle_v3(frame, laser_point=None, img_cv=None):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)- 返回椭圆参数版本
|
||||
增加红色圆圈检测,验证黄色圆圈是否为真正的靶心
|
||||
如果提供 laser_point,会选择最接近激光点的目标
|
||||
优化:
|
||||
1. 缩图到 MAX_DET_DIM 后再做 HSV/形态学,最长边 640->320 可获得 ~4x 加速
|
||||
2. 红色掩码在黄色轮廓循环外只计算一次,避免 N 次重复计算
|
||||
3. img_cv 可由外部传入(与其他线程共享转换结果),为 None 时自动转换
|
||||
Args:
|
||||
frame: 图像帧(img_cv 为 None 时使用)
|
||||
laser_point: 激光点坐标 (x, y),用于多目标场景下的目标选择
|
||||
img_cv: 已转换的 numpy BGR/RGB 图像;不为 None 时跳过 image2cv 转换
|
||||
Returns:
|
||||
(result_img, best_center, best_radius, method, best_radius1, ellipse_params)
|
||||
"""
|
||||
if img_cv is None:
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
from datetime import datetime
|
||||
print(f"[detect_circle_v3] begin {datetime.now()}")
|
||||
# -- 1. 缩图加速(与三角形路径保持一致)
|
||||
h_orig, w_orig = img_cv.shape[:2]
|
||||
MAX_DET_DIM = 480
|
||||
long_side = max(h_orig, w_orig)
|
||||
if long_side > MAX_DET_DIM:
|
||||
det_scale = MAX_DET_DIM / long_side
|
||||
img_det = cv2.resize(img_cv, (int(w_orig * det_scale), int(h_orig * det_scale)),
|
||||
interpolation=cv2.INTER_LINEAR)
|
||||
inv_scale = 1.0 / det_scale # 检测坐标 -> 原始坐标的倍率
|
||||
else:
|
||||
img_det = img_cv
|
||||
inv_scale = 1.0
|
||||
|
||||
# 激光点映射到检测分辨率
|
||||
lp_det = None
|
||||
if laser_point is not None:
|
||||
lp_det = (laser_point[0] / inv_scale, laser_point[1] / inv_scale)
|
||||
best_center = best_radius = best_radius1 = method = None
|
||||
ellipse_params = None
|
||||
|
||||
print(f"[detect_circle_v3] step 1 fin {datetime.now()}")
|
||||
|
||||
# -- 2. HSV + 黄色掩码
|
||||
hsv = cv2.cvtColor(img_det, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
hsv = cv2.merge((h, s, v))
|
||||
lower_yellow = np.array([7, 80, 0])
|
||||
upper_yellow = np.array([32, 255, 255])
|
||||
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
print(f"[detect_circle_v3] step 2 fin {datetime.now()}")
|
||||
|
||||
# -- 3. 红色掩码:在循环外只算一次
|
||||
mask_red = cv2.bitwise_or(
|
||||
cv2.inRange(hsv, np.array([0, 50, 40]), np.array([10, 255, 255])),
|
||||
cv2.inRange(hsv, np.array([170, 50, 40]), np.array([180, 255, 255])),
|
||||
)
|
||||
kernel_red = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel_red)
|
||||
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# 预先把红色轮廓筛选成 (center, radius) 列表,后续直接查表
|
||||
red_candidates = []
|
||||
for cnt_r in contours_red:
|
||||
ar = cv2.contourArea(cnt_r)
|
||||
if ar <= 10:
|
||||
continue
|
||||
pr = cv2.arcLength(cnt_r, True)
|
||||
if pr <= 0 or (4 * np.pi * ar) / (pr * pr) <= 0.3:
|
||||
continue
|
||||
if len(cnt_r) >= 5:
|
||||
(xr, yr), (wr, hr), _ = cv2.fitEllipse(cnt_r)
|
||||
red_candidates.append({"center": (int(xr), int(yr)), "radius": int(min(wr, hr) / 2)})
|
||||
else:
|
||||
(xr, yr), rr = cv2.minEnclosingCircle(cnt_r)
|
||||
red_candidates.append({"center": (int(xr), int(yr)), "radius": int(rr)})
|
||||
|
||||
print(f"[detect_circle_v3] step 3 fin {datetime.now()}")
|
||||
|
||||
# -- 4. 黄色轮廓循环(复用上面的红色候选列表)
|
||||
contours_yellow, _ = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
valid_targets = []
|
||||
for cnt_yellow in contours_yellow:
|
||||
area = cv2.contourArea(cnt_yellow)
|
||||
if area <= 15:
|
||||
continue
|
||||
perimeter = cv2.arcLength(cnt_yellow, True)
|
||||
if perimeter <= 0:
|
||||
continue
|
||||
circularity = (4 * np.pi * area) / (perimeter * perimeter)
|
||||
if circularity <= 0.5:
|
||||
continue
|
||||
print(f"[target] -> 面积:{area:.1f}, 圆度:{circularity:.2f}")
|
||||
if len(cnt_yellow) >= 5:
|
||||
(x, y), (width, height), angle = cv2.fitEllipse(cnt_yellow)
|
||||
yellow_ellipse = ((x, y), (width, height), angle)
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(min(width, height) / 2)
|
||||
else:
|
||||
(x, y), radius = cv2.minEnclosingCircle(cnt_yellow)
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(radius)
|
||||
yellow_ellipse = None
|
||||
# 在预筛好的红色候选中匹配
|
||||
matched = False
|
||||
for rc in red_candidates:
|
||||
ddx = yellow_center[0] - rc["center"][0]
|
||||
ddy = yellow_center[1] - rc["center"][1]
|
||||
dist_centers = math.hypot(ddx, ddy)
|
||||
if dist_centers < yellow_radius * 1.5 and rc["radius"] > yellow_radius * 0.7:
|
||||
print(f"[target] -> 找到匹配的红圈: 黄心({yellow_center}), "
|
||||
f"红心({rc['center']}), 距离:{dist_centers:.1f}, "
|
||||
f"黄半径:{yellow_radius}, 红半径:{rc['radius']}")
|
||||
valid_targets.append({
|
||||
"center": yellow_center,
|
||||
"radius": yellow_radius,
|
||||
"ellipse": yellow_ellipse,
|
||||
"area": area,
|
||||
})
|
||||
matched = True
|
||||
break
|
||||
if not matched :
|
||||
print("Debug -> 未找到匹配的红色圆圈,可能是误识别")
|
||||
|
||||
print(f"[detect_circle_v3] step 4 fin {datetime.now()}")
|
||||
|
||||
# -- 5. 选最佳目标,坐标还原到原始分辨率
|
||||
if valid_targets:
|
||||
if lp_det:
|
||||
best_target = min(valid_targets,
|
||||
key=lambda t: (t["center"][0] - lp_det[0]) ** 2
|
||||
+ (t["center"][1] - lp_det[1]) ** 2)
|
||||
method = "v3_ellipse_red_validated_laser_selected"
|
||||
else:
|
||||
best_target = max(valid_targets, key=lambda t: t["area"])
|
||||
method = "v3_ellipse_red_validated"
|
||||
bc = best_target["center"]
|
||||
br = best_target["radius"]
|
||||
be = best_target["ellipse"]
|
||||
if inv_scale != 1.0:
|
||||
best_center = (int(bc[0] * inv_scale), int(bc[1] * inv_scale))
|
||||
best_radius = int(br * inv_scale)
|
||||
if be is not None:
|
||||
(ex, ey), (ew, eh), ea = be
|
||||
be = ((ex * inv_scale, ey * inv_scale),
|
||||
(ew * inv_scale, eh * inv_scale), ea)
|
||||
else:
|
||||
best_center = bc
|
||||
best_radius = br
|
||||
ellipse_params = be
|
||||
best_radius1 = best_radius * 5
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
print(f"[detect_circle_v3] step 5 fin {datetime.now()}")
|
||||
return result_img, best_center, best_radius, method, best_radius1, ellipse_params
|
||||
|
||||
|
||||
def run_offline_test(image_path):
|
||||
"""读取图片,检测圆,绘制结果,保存图片"""
|
||||
|
||||
# 1. 检查文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 找不到图片文件: {image_path}")
|
||||
return
|
||||
|
||||
# 2. 使用 maix.image 读取图片 (适配 MaixPy v4)
|
||||
try:
|
||||
# 使用 image.load 读取文件,返回 Image 对象
|
||||
img = image.load(image_path)
|
||||
print(f"[INFO] 成功读取图片: {image_path} (尺寸: {img.width()}x{img.height()})")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 读取图片失败: {e}")
|
||||
print("提示:请确认 MaixPy 版本是否为 v4,且图片路径正确。")
|
||||
return
|
||||
|
||||
# 3. 调用 detect_circle_v3 函数
|
||||
print("[INFO] 正在调用 detect_circle_v3 进行检测...")
|
||||
start_time = time.ticks_ms()
|
||||
|
||||
result_img, center, radius, method, radius1, ellipse_params = detect_circle_v3(img)
|
||||
|
||||
cost_time = time.ticks_ms() - start_time
|
||||
print(f"[INFO] 检测完成,耗时: {cost_time}ms")
|
||||
print(f" 结果 -> 圆心: {center}, 半径: {radius}, 方法: {method}")
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
print(
|
||||
f" 椭圆 -> 中心: ({ell_center[0]:.1f}, {ell_center[1]:.1f}), 长轴: {max(width, height):.1f}, 短轴: {min(width, height):.1f}, 角度: {angle:.1f}°")
|
||||
|
||||
# 4. 绘制辅助线(可选,用于调试)
|
||||
if center and radius:
|
||||
# 为了绘制椭圆,需要转换回 cv2 图像
|
||||
img_cv = image.image2cv(result_img, False, False)
|
||||
|
||||
cx, cy = center
|
||||
|
||||
# 如果有椭圆参数,绘制椭圆
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
cx_ell, cy_ell = int(ell_center[0]), int(ell_center[1])
|
||||
|
||||
# 确定长轴和短轴
|
||||
if width >= height:
|
||||
# width 是长轴,height 是短轴
|
||||
axes_major = width
|
||||
axes_minor = height
|
||||
major_angle = angle # 长轴角度就是 angle
|
||||
minor_angle = angle + 90 # 短轴角度 = 长轴角度 + 90度
|
||||
else:
|
||||
# height 是长轴,width 是短轴
|
||||
axes_major = height
|
||||
axes_minor = width
|
||||
major_angle = angle + 90 # 长轴角度 = width角度 + 90度
|
||||
minor_angle = angle # 短轴角度就是 angle
|
||||
|
||||
# 使用 OpenCV 绘制椭圆(绿色,线宽2)
|
||||
cv2.ellipse(img_cv,
|
||||
(cx_ell, cy_ell), # 中心点
|
||||
(int(width / 2), int(height / 2)), # 半宽、半高
|
||||
angle, # 旋转角度(OpenCV需要原始angle)
|
||||
0, 360, # 起始和结束角度
|
||||
(0, 255, 0), # 绿色 (RGB格式)
|
||||
2) # 线宽
|
||||
|
||||
# 绘制椭圆中心点(红色)
|
||||
cv2.circle(img_cv, (cx_ell, cy_ell), 3, (255, 0, 0), -1)
|
||||
|
||||
import math
|
||||
# 绘制短轴(蓝色线条)
|
||||
minor_length = axes_minor / 2
|
||||
minor_angle_rad = math.radians(minor_angle)
|
||||
dx_minor = minor_length * math.cos(minor_angle_rad)
|
||||
dy_minor = minor_length * math.sin(minor_angle_rad)
|
||||
pt1_minor = (int(cx_ell - dx_minor), int(cy_ell - dy_minor))
|
||||
pt2_minor = (int(cx_ell + dx_minor), int(cy_ell + dy_minor))
|
||||
cv2.line(img_cv, pt1_minor, pt2_minor, (0, 0, 255), 2) # 蓝色 (RGB格式)
|
||||
else:
|
||||
# 如果没有椭圆参数,绘制圆形(红色)
|
||||
cv2.circle(img_cv, (cx, cy), radius, (0, 0, 255), 2)
|
||||
cv2.circle(img_cv, (cx, cy), 2, (0, 0, 255), -1)
|
||||
|
||||
# 转换回 maix image
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
|
||||
# 定义颜色对象用于文字
|
||||
try:
|
||||
color_black = image.Color.from_rgb(0, 0, 0)
|
||||
except AttributeError:
|
||||
color_black = image.Color(0, 0, 0)
|
||||
|
||||
# D. 添加文字信息
|
||||
FOCAL_LENGTH_PIX = 1900
|
||||
d = (REAL_RADIUS_CM * FOCAL_LENGTH_PIX) / radius1 / 100.0
|
||||
info_str = f"R:{radius} M:{method} D:{d:.2f}"
|
||||
print(info_str)
|
||||
|
||||
# 计算文字位置,防止超出图片边界
|
||||
r_outer = int(radius * 11.0) if radius else 100
|
||||
text_y = cy - r_outer - 20 if cy > r_outer + 20 else cy + r_outer + 20
|
||||
|
||||
# 调用 draw_string
|
||||
result_img.draw_string(0, 0, info_str, color=color_black, scale=1.0)
|
||||
|
||||
# 5. 保存结果图片
|
||||
base, ext = os.path.splitext(image_path)
|
||||
output_path = f"{base}_result{ext}"
|
||||
try:
|
||||
result_img.save(output_path, quality=100)
|
||||
print(f"[SUCCESS] 结果已保存至: {output_path}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 保存图片失败: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# ================= 配置区域 =================
|
||||
|
||||
# 1. 设置要测试的图片路径
|
||||
# 建议将图片放在与脚本同级目录,或者使用绝对路径
|
||||
TARGET_IMAGE = "/root/phot/None_314_258_0_0041.bmp"
|
||||
|
||||
TARGET_DIR = "/root/phot" # 修改为你想要读取的目录路径
|
||||
|
||||
# 支持的图片格式
|
||||
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp']
|
||||
|
||||
# ================= 执行区域 =================
|
||||
if 'TARGET_DIR' in locals():
|
||||
# 读取目录下所有图片文件,过滤掉 _result.jpg 后缀的文件
|
||||
image_files = []
|
||||
if os.path.exists(TARGET_DIR) and os.path.isdir(TARGET_DIR):
|
||||
for filename in os.listdir(TARGET_DIR):
|
||||
# 检查文件扩展名
|
||||
if any(filename.lower().endswith(ext) for ext in IMAGE_EXTENSIONS):
|
||||
# 过滤掉 _result.jpg 后缀的文件
|
||||
if not filename.endswith('_result.jpg'):
|
||||
filepath = os.path.join(TARGET_DIR, filename)
|
||||
if os.path.isfile(filepath):
|
||||
image_files.append(filepath)
|
||||
|
||||
# 按文件名排序(可选)
|
||||
image_files.sort()
|
||||
|
||||
print(f"[INFO] 在目录 {TARGET_DIR} 中找到 {len(image_files)} 张图片")
|
||||
|
||||
# 处理每张图片
|
||||
for img_path in image_files:
|
||||
print(f"\n{'=' * 10} 开始处理: {img_path} {'=' * 10}")
|
||||
run_offline_test(img_path)
|
||||
else:
|
||||
print(f"[ERROR] 目录不存在或不是有效目录: {TARGET_DIR}")
|
||||
|
||||
else:
|
||||
run_offline_test(TARGET_IMAGE)
|
||||
@@ -0,0 +1,620 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
离线测试脚本:直接复用 detect_circle 逻辑进行测试
|
||||
运行环境:MaixPy (Sipeed MAIX)
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
# import time
|
||||
from maix import image,time
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ==================== 全局配置 (与 test_main.py 保持一致) ====================
|
||||
REAL_RADIUS_CM = 20 # 靶心实际半径(厘米)
|
||||
|
||||
# ==================== 复制的核心算法 ====================
|
||||
# 注意:这里直接复制了 detect_circle 的逻辑,避免 import main 导致的冲突
|
||||
|
||||
|
||||
def detect_circle_v3(frame, laser_point=None):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)- 返回椭圆参数版本
|
||||
增加红色圆圈检测,验证黄色圆圈是否为真正的靶心
|
||||
如果提供 laser_point,会选择最接近激光点的目标
|
||||
|
||||
Args:
|
||||
frame: 图像帧
|
||||
laser_point: 激光点坐标 (x, y),用于多目标场景下的目标选择
|
||||
|
||||
Returns:
|
||||
(result_img, best_center, best_radius, method, best_radius1, ellipse_params)
|
||||
"""
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
|
||||
best_center = best_radius = best_radius1 = method = None
|
||||
ellipse_params = None
|
||||
|
||||
# HSV 黄色掩码检测(模糊靶心)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 调整饱和度策略:稍微增强,不要过度
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 调整形态学操作
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
contours_yellow, _ = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
# 存储所有有效的黄色-红色组合
|
||||
valid_targets = []
|
||||
|
||||
if contours_yellow:
|
||||
for cnt_yellow in contours_yellow:
|
||||
area = cv2.contourArea(cnt_yellow)
|
||||
perimeter = cv2.arcLength(cnt_yellow, True)
|
||||
|
||||
# 计算圆度
|
||||
if perimeter > 0:
|
||||
circularity = (4 * np.pi * area) / (perimeter * perimeter)
|
||||
else:
|
||||
circularity = 0
|
||||
|
||||
logger = get_logger()
|
||||
if area > 50 and circularity > 0.7:
|
||||
if logger:
|
||||
logger.info(f"[target] -> 面积:{area}, 圆度:{circularity:.2f}")
|
||||
# 尝试拟合椭圆
|
||||
yellow_center = None
|
||||
yellow_radius = None
|
||||
yellow_ellipse = None
|
||||
|
||||
if len(cnt_yellow) >= 5:
|
||||
(x, y), (width, height), angle = cv2.fitEllipse(cnt_yellow)
|
||||
yellow_ellipse = ((x, y), (width, height), angle)
|
||||
axes_minor = min(width, height)
|
||||
radius = axes_minor / 2
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(radius)
|
||||
else:
|
||||
(x, y), radius = cv2.minEnclosingCircle(cnt_yellow)
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(radius)
|
||||
yellow_ellipse = None
|
||||
|
||||
# 如果检测到黄色圆圈,再检测红色圆圈进行验证
|
||||
if yellow_center and yellow_radius:
|
||||
# HSV 红色掩码检测(红色在HSV中跨越0度,需要两个范围)
|
||||
# 红色范围1: 0-10度(接近0度的红色)
|
||||
lower_red1 = np.array([0, 80, 0])
|
||||
upper_red1 = np.array([10, 255, 255])
|
||||
mask_red1 = cv2.inRange(hsv, lower_red1, upper_red1)
|
||||
|
||||
# 红色范围2: 170-180度(接近180度的红色)
|
||||
lower_red2 = np.array([170, 80, 0])
|
||||
upper_red2 = np.array([180, 255, 255])
|
||||
mask_red2 = cv2.inRange(hsv, lower_red2, upper_red2)
|
||||
|
||||
# 合并两个红色掩码
|
||||
mask_red = cv2.bitwise_or(mask_red1, mask_red2)
|
||||
|
||||
# 形态学操作
|
||||
kernel_red = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel_red)
|
||||
|
||||
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
found_valid_red = False
|
||||
|
||||
if contours_red:
|
||||
# 找到所有符合条件的红色圆圈
|
||||
for cnt_red in contours_red:
|
||||
area_red = cv2.contourArea(cnt_red)
|
||||
perimeter_red = cv2.arcLength(cnt_red, True)
|
||||
|
||||
if perimeter_red > 0:
|
||||
circularity_red = (4 * np.pi * area_red) / (perimeter_red * perimeter_red)
|
||||
else:
|
||||
circularity_red = 0
|
||||
|
||||
# 红色圆圈也应该有一定的圆度
|
||||
if area_red > 50 and circularity_red > 0.6:
|
||||
# 计算红色圆圈的中心和半径
|
||||
if len(cnt_red) >= 5:
|
||||
(x_red, y_red), (w_red, h_red), angle_red = cv2.fitEllipse(cnt_red)
|
||||
radius_red = min(w_red, h_red) / 2
|
||||
red_center = (int(x_red), int(y_red))
|
||||
red_radius = int(radius_red)
|
||||
else:
|
||||
(x_red, y_red), radius_red = cv2.minEnclosingCircle(cnt_red)
|
||||
red_center = (int(x_red), int(y_red))
|
||||
red_radius = int(radius_red)
|
||||
|
||||
# 计算黄色和红色圆心的距离
|
||||
if red_center:
|
||||
dx = yellow_center[0] - red_center[0]
|
||||
dy = yellow_center[1] - red_center[1]
|
||||
distance = np.sqrt(dx*dx + dy*dy)
|
||||
|
||||
# 圆心距离阈值:应该小于黄色半径的某个倍数(比如1.5倍)
|
||||
max_distance = yellow_radius * 1.5
|
||||
|
||||
# 红色圆圈应该比黄色圆圈大(外圈)
|
||||
if distance < max_distance and red_radius > yellow_radius * 0.8:
|
||||
found_valid_red = True
|
||||
logger = get_logger()
|
||||
if logger:
|
||||
logger.info(f"[target] -> 找到匹配的红圈: 黄心({yellow_center}), 红心({red_center}), 距离:{distance:.1f}, 黄半径:{yellow_radius}, 红半径:{red_radius}")
|
||||
|
||||
# 记录这个有效目标
|
||||
valid_targets.append({
|
||||
'center': yellow_center,
|
||||
'radius': yellow_radius,
|
||||
'ellipse': yellow_ellipse,
|
||||
'area': area
|
||||
})
|
||||
break
|
||||
|
||||
if not found_valid_red:
|
||||
logger = get_logger()
|
||||
if logger:
|
||||
logger.debug("Debug -> 未找到匹配的红色圆圈,可能是误识别")
|
||||
|
||||
# 从所有有效目标中选择最佳目标
|
||||
if valid_targets:
|
||||
if laser_point:
|
||||
# 如果有激光点,选择最接近激光点的目标
|
||||
best_target = None
|
||||
min_distance = float('inf')
|
||||
for target in valid_targets:
|
||||
dx = target['center'][0] - laser_point[0]
|
||||
dy = target['center'][1] - laser_point[1]
|
||||
distance = np.sqrt(dx*dx + dy*dy)
|
||||
if distance < min_distance:
|
||||
min_distance = distance
|
||||
best_target = target
|
||||
if best_target:
|
||||
best_center = best_target['center']
|
||||
best_radius = best_target['radius']
|
||||
ellipse_params = best_target['ellipse']
|
||||
method = "v3_ellipse_red_validated_laser_selected"
|
||||
best_radius1 = best_radius * 5
|
||||
else:
|
||||
# 如果没有激光点,选择面积最大的目标
|
||||
best_target = max(valid_targets, key=lambda t: t['area'])
|
||||
best_center = best_target['center']
|
||||
best_radius = best_target['radius']
|
||||
ellipse_params = best_target['ellipse']
|
||||
method = "v3_ellipse_red_validated"
|
||||
best_radius1 = best_radius * 5
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1, ellipse_params
|
||||
|
||||
def detect_circle(frame):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)"""
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
# gray = cv2.cvtColor(img_cv, cv2.COLOR_RGB2GRAY)
|
||||
# blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
||||
# edged = cv2.Canny(blurred, 50, 150)
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# ceroded = cv2.erode(cv2.dilate(edged, kernel), kernel)
|
||||
|
||||
# contours, _ = cv2.findContours(ceroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# best_center = best_radius = best_radius1 = method = None
|
||||
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
# s = np.clip(s * 2, 0, 255).astype(np.uint8)
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
# lower_yellow = np.array([7, 80, 0])
|
||||
# upper_yellow = np.array([32, 255, 182])
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# auto
|
||||
# R:31 M:v2 D:2.410110127692767
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
|
||||
# # 1. 增强饱和度(模糊照片需要更强的增强)
|
||||
# s = np.clip(s * 2.5, 0, 255).astype(np.uint8) # 从2.0改为2.5
|
||||
|
||||
# # 2. 增强亮度(模糊照片可能偏暗)
|
||||
# v = np.clip(v * 1.2, 0, 255).astype(np.uint8) # 新增:提升亮度
|
||||
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
|
||||
# # 3. 放宽HSV颜色范围(特别是模糊照片)
|
||||
# # 降低饱和度下限,提高亮度上限
|
||||
# lower_yellow = np.array([5, 50, 30]) # H:5-35, S:50-255, V:30-255
|
||||
# upper_yellow = np.array([35, 255, 255])
|
||||
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# # 4. 增强形态学操作(连接被分割的区域)
|
||||
# kernel_small = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# kernel_large = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)) # 更大的核
|
||||
|
||||
# # 先开运算去除噪声
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_small)
|
||||
# # 多次膨胀连接区域(模糊照片需要更多膨胀)
|
||||
# mask = cv2.dilate(mask, kernel_large, iterations=2) # 增加迭代次数
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel_large) # 闭运算填充空洞
|
||||
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# area = cv2.contourArea(largest)
|
||||
# if area > 50:
|
||||
# # 5. 使用面积计算等效半径(更准确)
|
||||
# equivalent_radius = np.sqrt(area / np.pi)
|
||||
|
||||
# # 6. 同时使用minEnclosingCircle作为备选(取较大值)
|
||||
# (x, y), enclosing_radius = cv2.minEnclosingCircle(largest)
|
||||
|
||||
# # 取两者中的较大值,确保不遗漏
|
||||
# radius = max(equivalent_radius, enclosing_radius)
|
||||
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# codegee
|
||||
# R:24 M:v2 D:3.061493895819174
|
||||
# R:22 M:v2 D:3.3644971681267077 np.clip(s * 1.1, 0, 255)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 2. 调整饱和度策略:
|
||||
# 不要暴力翻倍,可以尝试稍微增强,或者使用 CLAHE 增强亮度/对比度
|
||||
# 这里我们稍微增加一点饱和度,并确保不溢出
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
# 对亮度通道 v 也可以做一点 CLAHE 处理来增强对比度(可选)
|
||||
# clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
||||
# v = clahe.apply(v)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 3. 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
# 降低 S 的下限 (80 -> 35),提高 V 的上限 (182 -> 255)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 4. 调整形态学操作
|
||||
# 去掉 MORPH_OPEN,因为它会减小面积。
|
||||
# 使用 MORPH_CLOSE (先膨胀后腐蚀) 来填充内部小黑洞,连接近邻区域
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
# 再进行一次膨胀,确保边缘被包含进来
|
||||
# mask = cv2.dilate(mask, kernel, iterations=1)
|
||||
|
||||
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
if contours:
|
||||
largest = max(contours, key=cv2.contourArea)
|
||||
|
||||
# 这里可以适当降低面积阈值,或者保持不变
|
||||
if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
|
||||
# --- 核心修改开始 ---
|
||||
# 1. 尝试拟合椭圆 (需要轮廓点至少为5个)
|
||||
if len(largest) >= 5:
|
||||
# 返回值: ((中心x, 中心y), (长轴, 短轴), 旋转角度)
|
||||
(x, y), (axes_major, axes_minor), angle = cv2.fitEllipse(largest)
|
||||
|
||||
# 2. 计算半径
|
||||
# 选项A:取长短轴的平均值 (比较稳健)
|
||||
# radius = (axes_major + axes_minor) / 4
|
||||
|
||||
# 选项B:直接取短轴的一半 (抗模糊最强,推荐)
|
||||
radius = axes_minor / 2
|
||||
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2_ellipse"
|
||||
else:
|
||||
# 如果点太少无法拟合椭圆,降级回 minEnclosingCircle
|
||||
(x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2"
|
||||
# --- 核心修改结束 ---
|
||||
|
||||
# 你的后续逻辑
|
||||
best_radius1 = radius * 5
|
||||
|
||||
|
||||
# operas 4.5
|
||||
# R:25 M:v2 D:2.9554872521538527
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
|
||||
# # 1. 适度增强饱和度(不要过度,否则噪声也会增强)
|
||||
# s = np.clip(s * 1.5, 0, 255).astype(np.uint8)
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
|
||||
# # 2. 放宽 HSV 阈值范围(关键改动)
|
||||
# # - 饱和度下限从 80 降到 40(捕捉淡黄色)
|
||||
# # - 亮度上限从 182 提高到 255(允许更亮的黄色)
|
||||
# lower_yellow = np.array([7, 40, 30])
|
||||
# upper_yellow = np.array([35, 255, 255])
|
||||
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# # 3. 调整形态学操作:用 CLOSE 替代 OPEN
|
||||
# # CLOSE(先膨胀后腐蚀):填充内部空洞,连接相邻区域
|
||||
# # OPEN(先腐蚀后膨胀):会缩小区域,不适合模糊图像
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) # 稍大的核
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
# mask = cv2.dilate(mask, kernel, iterations=1) # 额外膨胀,确保边缘被包含
|
||||
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# # --- 新增:将 Mask 叠加到原图上用于调试 ---
|
||||
# # 创建一个彩色掩码(红色通道为255,其他为0)
|
||||
# mask_overlay = np.zeros_like(img_cv)
|
||||
# mask_overlay[:, :, 2] = mask # 将掩码放在红色通道 (BGR中的R)
|
||||
#
|
||||
# cv2.addWeighted(img_cv, 0.6, mask_overlay, 0.4, 0, img_cv)
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1
|
||||
|
||||
|
||||
def detect_circle_v2(frame):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)- 返回椭圆参数版本"""
|
||||
global REAL_RADIUS_CM
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
|
||||
best_center = best_radius = best_radius1 = method = None
|
||||
ellipse_params = None # 存储椭圆参数 ((x, y), (axes_major, axes_minor), angle)
|
||||
|
||||
# HSV 黄色掩码检测(模糊靶心)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 调整饱和度策略:稍微增强,不要过度
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 调整形态学操作
|
||||
# 使用 MORPH_CLOSE (先膨胀后腐蚀) 来填充内部小黑洞,连接近邻区域
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
if contours:
|
||||
largest = max(contours, key=cv2.contourArea)
|
||||
|
||||
if cv2.contourArea(largest) > 50:
|
||||
# 尝试拟合椭圆 (需要轮廓点至少为5个)
|
||||
if len(largest) >= 5:
|
||||
# 返回值: ((中心x, 中心y), (width, height), 旋转角度)
|
||||
# 注意:width 和 height 是外接矩形的尺寸,不是长轴和短轴
|
||||
(x, y), (width, height), angle = cv2.fitEllipse(largest)
|
||||
|
||||
# 保存椭圆参数(保持原始顺序,用于绘制)
|
||||
ellipse_params = ((x, y), (width, height), angle)
|
||||
|
||||
# 计算半径:使用较小的尺寸作为短轴
|
||||
axes_minor = min(width, height)
|
||||
radius = axes_minor / 2
|
||||
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2_ellipse"
|
||||
else:
|
||||
# 如果点太少无法拟合椭圆,降级回 minEnclosingCircle
|
||||
(x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2"
|
||||
ellipse_params = None # 圆形,没有椭圆参数
|
||||
|
||||
best_radius1 = radius * 5
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1, ellipse_params
|
||||
|
||||
# ==================== 测试逻辑 ====================
|
||||
|
||||
def run_offline_test(image_path):
|
||||
"""读取图片,检测圆,绘制结果,保存图片"""
|
||||
|
||||
# 1. 检查文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 找不到图片文件: {image_path}")
|
||||
return
|
||||
|
||||
# 2. 使用 maix.image 读取图片 (适配 MaixPy v4)
|
||||
try:
|
||||
# 使用 image.load 读取文件,返回 Image 对象
|
||||
img = image.load(image_path)
|
||||
print(f"[INFO] 成功读取图片: {image_path} (尺寸: {img.width()}x{img.height()})")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 读取图片失败: {e}")
|
||||
print("提示:请确认 MaixPy 版本是否为 v4,且图片路径正确。")
|
||||
return
|
||||
|
||||
|
||||
# 3. 调用 detect_circle_v2 函数
|
||||
print("[INFO] 正在调用 detect_circle_v2 进行检测...")
|
||||
start_time = time.ticks_ms()
|
||||
|
||||
result_img, center, radius, method, radius1, ellipse_params = detect_circle_v3(img)
|
||||
|
||||
cost_time = time.ticks_ms() - start_time
|
||||
print(f"[INFO] 检测完成,耗时: {cost_time}ms")
|
||||
print(f" 结果 -> 圆心: {center}, 半径: {radius}, 方法: {method}")
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
print(f" 椭圆 -> 中心: ({ell_center[0]:.1f}, {ell_center[1]:.1f}), 长轴: {max(width, height):.1f}, 短轴: {min(width, height):.1f}, 角度: {angle:.1f}°")
|
||||
|
||||
# 4. 绘制辅助线(可选,用于调试)
|
||||
if center and radius:
|
||||
# 为了绘制椭圆,需要转换回 cv2 图像
|
||||
img_cv = image.image2cv(result_img, False, False)
|
||||
|
||||
cx, cy = center
|
||||
|
||||
# 如果有椭圆参数,绘制椭圆
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
cx_ell, cy_ell = int(ell_center[0]), int(ell_center[1])
|
||||
|
||||
# 确定长轴和短轴
|
||||
if width >= height:
|
||||
# width 是长轴,height 是短轴
|
||||
axes_major = width
|
||||
axes_minor = height
|
||||
major_angle = angle # 长轴角度就是 angle
|
||||
minor_angle = angle + 90 # 短轴角度 = 长轴角度 + 90度
|
||||
else:
|
||||
# height 是长轴,width 是短轴
|
||||
axes_major = height
|
||||
axes_minor = width
|
||||
major_angle = angle + 90 # 长轴角度 = width角度 + 90度
|
||||
minor_angle = angle # 短轴角度就是 angle
|
||||
|
||||
# 使用 OpenCV 绘制椭圆(绿色,线宽2)
|
||||
cv2.ellipse(img_cv,
|
||||
(cx_ell, cy_ell), # 中心点
|
||||
(int(width/2), int(height/2)), # 半宽、半高
|
||||
angle, # 旋转角度(OpenCV需要原始angle)
|
||||
0, 360, # 起始和结束角度
|
||||
(0, 255, 0), # 绿色 (RGB格式)
|
||||
2) # 线宽
|
||||
|
||||
# 绘制椭圆中心点(红色)
|
||||
cv2.circle(img_cv, (cx_ell, cy_ell), 3, (255, 0, 0), -1)
|
||||
|
||||
import math
|
||||
# 绘制短轴(蓝色线条)
|
||||
minor_length = axes_minor / 2
|
||||
minor_angle_rad = math.radians(minor_angle)
|
||||
dx_minor = minor_length * math.cos(minor_angle_rad)
|
||||
dy_minor = minor_length * math.sin(minor_angle_rad)
|
||||
pt1_minor = (int(cx_ell - dx_minor), int(cy_ell - dy_minor))
|
||||
pt2_minor = (int(cx_ell + dx_minor), int(cy_ell + dy_minor))
|
||||
cv2.line(img_cv, pt1_minor, pt2_minor, (0, 0, 255), 2) # 蓝色 (RGB格式)
|
||||
else:
|
||||
# 如果没有椭圆参数,绘制圆形(红色)
|
||||
cv2.circle(img_cv, (cx, cy), radius, (0, 0, 255), 2)
|
||||
cv2.circle(img_cv, (cx, cy), 2, (0, 0, 255), -1)
|
||||
|
||||
# 转换回 maix image
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
|
||||
# 定义颜色对象用于文字
|
||||
try:
|
||||
color_black = image.Color.from_rgb(0,0,0)
|
||||
except AttributeError:
|
||||
color_black = image.Color(0,0,0)
|
||||
|
||||
# D. 添加文字信息
|
||||
FOCAL_LENGTH_PIX = 1900
|
||||
d = (REAL_RADIUS_CM * FOCAL_LENGTH_PIX) / radius1 / 100.0
|
||||
info_str = f"R:{radius} M:{method} D:{d:.2f}"
|
||||
print(info_str)
|
||||
|
||||
# 计算文字位置,防止超出图片边界
|
||||
r_outer = int(radius * 11.0) if radius else 100
|
||||
text_y = cy - r_outer - 20 if cy > r_outer + 20 else cy + r_outer + 20
|
||||
|
||||
# 调用 draw_string
|
||||
result_img.draw_string(0, 0, info_str, color=color_black, scale=1.0)
|
||||
|
||||
|
||||
# 5. 保存结果图片
|
||||
output_path = image_path.replace(".bmp", "_result.bmp")
|
||||
output_path = image_path.replace(".jpg", "_result.jpg")
|
||||
try:
|
||||
result_img.save(output_path, quality=100)
|
||||
print(f"[SUCCESS] 结果已保存至: {output_path}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 保存图片失败: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
# ================= 配置区域 =================
|
||||
|
||||
# 1. 设置要测试的图片路径
|
||||
# 建议将图片放在与脚本同级目录,或者使用绝对路径
|
||||
TARGET_IMAGE = "/root/phot/None_314_258_0_0041.bmp"
|
||||
|
||||
# TARGET_DIR = "/root/phot_test2" # 修改为你想要读取的目录路径
|
||||
|
||||
# 支持的图片格式
|
||||
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp']
|
||||
|
||||
# ================= 执行区域 =================
|
||||
if 'TARGET_DIR' in locals():
|
||||
# 读取目录下所有图片文件,过滤掉 _result.jpg 后缀的文件
|
||||
image_files = []
|
||||
if os.path.exists(TARGET_DIR) and os.path.isdir(TARGET_DIR):
|
||||
for filename in os.listdir(TARGET_DIR):
|
||||
# 检查文件扩展名
|
||||
if any(filename.lower().endswith(ext) for ext in IMAGE_EXTENSIONS):
|
||||
# 过滤掉 _result.jpg 后缀的文件
|
||||
if not filename.endswith('_result.jpg'):
|
||||
filepath = os.path.join(TARGET_DIR, filename)
|
||||
if os.path.isfile(filepath):
|
||||
image_files.append(filepath)
|
||||
|
||||
# 按文件名排序(可选)
|
||||
image_files.sort()
|
||||
|
||||
print(f"[INFO] 在目录 {TARGET_DIR} 中找到 {len(image_files)} 张图片")
|
||||
|
||||
# 处理每张图片
|
||||
for img_path in image_files:
|
||||
print(f"\n{'='*10} 开始处理: {img_path} {'='*10}")
|
||||
run_offline_test(img_path)
|
||||
else:
|
||||
print(f"[ERROR] 目录不存在或不是有效目录: {TARGET_DIR}")
|
||||
|
||||
else:
|
||||
run_offline_test(TARGET_IMAGE)
|
||||
@@ -0,0 +1,635 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
离线测试脚本:直接复用 detect_circle 逻辑进行测试
|
||||
运行环境:MaixPy (Sipeed MAIX)
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
# import time
|
||||
from maix import image, time
|
||||
import cv2
|
||||
import numpy as np
|
||||
|
||||
# ==================== 全局配置 (与 test_main.py 保持一致) ====================
|
||||
REAL_RADIUS_CM = 20 # 靶心实际半径(厘米)
|
||||
|
||||
|
||||
# ==================== 复制的核心算法 ====================
|
||||
# 注意:这里直接复制了 detect_circle 的逻辑,避免 import main 导致的冲突
|
||||
|
||||
|
||||
def detect_circle_v3(frame, laser_point=None):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)- 返回椭圆参数版本
|
||||
增加红色圆圈检测,验证黄色圆圈是否为真正的靶心
|
||||
如果提供 laser_point,会选择最接近激光点的目标
|
||||
|
||||
Args:
|
||||
frame: 图像帧
|
||||
laser_point: 激光点坐标 (x, y),用于多目标场景下的目标选择
|
||||
|
||||
Returns:
|
||||
(result_img, best_center, best_radius, method, best_radius1, ellipse_params)
|
||||
"""
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
|
||||
best_center = best_radius = best_radius1 = method = None
|
||||
ellipse_params = None
|
||||
|
||||
# HSV 黄色掩码检测(模糊靶心)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 调整饱和度策略:稍微增强,不要过度
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 调整形态学操作
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_yellow = cv2.morphologyEx(mask_yellow, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
contours_yellow, _ = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
# 存储所有有效的黄色-红色组合
|
||||
valid_targets = []
|
||||
|
||||
if contours_yellow:
|
||||
for cnt_yellow in contours_yellow:
|
||||
area = cv2.contourArea(cnt_yellow)
|
||||
perimeter = cv2.arcLength(cnt_yellow, True)
|
||||
|
||||
# 计算圆度
|
||||
if perimeter > 0:
|
||||
circularity = (4 * np.pi * area) / (perimeter * perimeter)
|
||||
else:
|
||||
circularity = 0
|
||||
|
||||
if area > 50 and circularity > 0.7:
|
||||
print(f"[target] -> 面积:{area}, 圆度:{circularity:.2f}")
|
||||
# 尝试拟合椭圆
|
||||
yellow_center = None
|
||||
yellow_radius = None
|
||||
yellow_ellipse = None
|
||||
|
||||
if len(cnt_yellow) >= 5:
|
||||
(x, y), (width, height), angle = cv2.fitEllipse(cnt_yellow)
|
||||
yellow_ellipse = ((x, y), (width, height), angle)
|
||||
axes_minor = min(width, height)
|
||||
radius = axes_minor / 2
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(radius)
|
||||
else:
|
||||
(x, y), radius = cv2.minEnclosingCircle(cnt_yellow)
|
||||
yellow_center = (int(x), int(y))
|
||||
yellow_radius = int(radius)
|
||||
yellow_ellipse = None
|
||||
|
||||
# 如果检测到黄色圆圈,再检测红色圆圈进行验证
|
||||
if yellow_center and yellow_radius:
|
||||
# HSV 红色掩码检测(红色在HSV中跨越0度,需要两个范围)
|
||||
# 红色范围1: 0-12度(接近0度的红色)
|
||||
# 放宽S/V阈值:S>=30, V>=20 以捕获淡红/暗红
|
||||
lower_red1 = np.array([0, 30, 20])
|
||||
upper_red1 = np.array([12, 255, 255])
|
||||
mask_red1 = cv2.inRange(hsv, lower_red1, upper_red1)
|
||||
|
||||
# 红色范围2: 168-180度(接近180度的红色)
|
||||
lower_red2 = np.array([168, 30, 20])
|
||||
upper_red2 = np.array([180, 255, 255])
|
||||
mask_red2 = cv2.inRange(hsv, lower_red2, upper_red2)
|
||||
|
||||
# 合并两个红色掩码
|
||||
mask_red = cv2.bitwise_or(mask_red1, mask_red2)
|
||||
|
||||
# 形态学操作:先CLOSE填充空洞,再DILATE加厚环状区域
|
||||
kernel_red = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask_red = cv2.morphologyEx(mask_red, cv2.MORPH_CLOSE, kernel_red)
|
||||
mask_red = cv2.dilate(mask_red, kernel_red, iterations=1)
|
||||
|
||||
contours_red, _ = cv2.findContours(mask_red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
red_pixel_count = np.sum(mask_red > 0)
|
||||
print(f"Debug -> 红色掩码: {red_pixel_count} 像素, {len(contours_red)} 个轮廓")
|
||||
|
||||
found_valid_red = False
|
||||
|
||||
if contours_red:
|
||||
for cnt_red in contours_red:
|
||||
area_red = cv2.contourArea(cnt_red)
|
||||
perimeter_red = cv2.arcLength(cnt_red, True)
|
||||
|
||||
if perimeter_red > 0:
|
||||
circularity_red = (4 * np.pi * area_red) / (perimeter_red * perimeter_red)
|
||||
else:
|
||||
circularity_red = 0
|
||||
|
||||
# 环状轮廓圆度可能偏低,放宽到0.2
|
||||
print(f"Debug -> 红轮廓: 面积={area_red:.1f}, 圆度={circularity_red:.2f}" +
|
||||
f" (面积>15={area_red > 15}, 圆度>0.2={circularity_red > 0.2})")
|
||||
if area_red > 15 and circularity_red > 0.2:
|
||||
if len(cnt_red) >= 5:
|
||||
(x_red, y_red), (w_red, h_red), angle_red = cv2.fitEllipse(cnt_red)
|
||||
radius_red = min(w_red, h_red) / 2
|
||||
red_center = (int(x_red), int(y_red))
|
||||
red_radius = int(radius_red)
|
||||
else:
|
||||
(x_red, y_red), radius_red = cv2.minEnclosingCircle(cnt_red)
|
||||
red_center = (int(x_red), int(y_red))
|
||||
red_radius = int(radius_red)
|
||||
|
||||
if red_center:
|
||||
dx = yellow_center[0] - red_center[0]
|
||||
dy = yellow_center[1] - red_center[1]
|
||||
distance = np.sqrt(dx * dx + dy * dy)
|
||||
|
||||
max_distance = yellow_radius * 2.0
|
||||
min_r = min(red_radius, yellow_radius)
|
||||
max_r = max(red_radius, yellow_radius)
|
||||
size_ratio = min_r / max_r if max_r > 0 else 0
|
||||
print(f"Debug -> 圆心距={distance:.1f}(阈值={max_distance:.1f}), "
|
||||
f"大小比={size_ratio:.2f}(阈值=0.5), "
|
||||
f"距离OK={distance < max_distance}, 大小OK={size_ratio > 0.5}")
|
||||
|
||||
# 允许红圈在黄圈外侧或内侧,只要大小相近(较小/较大 >= 0.5)
|
||||
if distance < max_distance and size_ratio > 0.5:
|
||||
found_valid_red = True
|
||||
print(
|
||||
f"[target] -> 找到匹配的红圈: 黄心({yellow_center}), 红心({red_center}), 距离:{distance:.1f}, 黄半径:{yellow_radius}, 红半径:{red_radius}")
|
||||
|
||||
valid_targets.append({
|
||||
'center': yellow_center,
|
||||
'radius': yellow_radius,
|
||||
'ellipse': yellow_ellipse,
|
||||
'area': area
|
||||
})
|
||||
break
|
||||
|
||||
if not found_valid_red:
|
||||
# 如果黄圈非常可靠(大且圆),在没有红圈验证时仍接受
|
||||
if area > 30 and circularity > 0.85:
|
||||
print(f"[target] -> 黄圈高置信度(面积:{area:.0f}, 圆度:{circularity:.2f}),跳过红圈验证直接接受")
|
||||
valid_targets.append({
|
||||
'center': yellow_center,
|
||||
'radius': yellow_radius,
|
||||
'ellipse': yellow_ellipse,
|
||||
'area': area
|
||||
})
|
||||
else:
|
||||
print("Debug -> 未找到匹配的红色圆圈,可能是误识别")
|
||||
|
||||
# 从所有有效目标中选择最佳目标
|
||||
if valid_targets:
|
||||
if laser_point:
|
||||
# 如果有激光点,选择最接近激光点的目标
|
||||
best_target = None
|
||||
min_distance = float('inf')
|
||||
for target in valid_targets:
|
||||
dx = target['center'][0] - laser_point[0]
|
||||
dy = target['center'][1] - laser_point[1]
|
||||
distance = np.sqrt(dx * dx + dy * dy)
|
||||
if distance < min_distance:
|
||||
min_distance = distance
|
||||
best_target = target
|
||||
if best_target:
|
||||
best_center = best_target['center']
|
||||
best_radius = best_target['radius']
|
||||
ellipse_params = best_target['ellipse']
|
||||
method = "v3_ellipse_red_validated_laser_selected"
|
||||
best_radius1 = best_radius * 5
|
||||
else:
|
||||
# 如果没有激光点,选择面积最大的目标
|
||||
best_target = max(valid_targets, key=lambda t: t['area'])
|
||||
best_center = best_target['center']
|
||||
best_radius = best_target['radius']
|
||||
ellipse_params = best_target['ellipse']
|
||||
method = "v3_ellipse_red_validated"
|
||||
best_radius1 = best_radius * 5
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1, ellipse_params
|
||||
|
||||
|
||||
def detect_circle(frame):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)"""
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
# gray = cv2.cvtColor(img_cv, cv2.COLOR_RGB2GRAY)
|
||||
# blurred = cv2.GaussianBlur(gray, (5, 5), 0)
|
||||
# edged = cv2.Canny(blurred, 50, 150)
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# ceroded = cv2.erode(cv2.dilate(edged, kernel), kernel)
|
||||
|
||||
# contours, _ = cv2.findContours(ceroded, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# best_center = best_radius = best_radius1 = method = None
|
||||
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
# s = np.clip(s * 2, 0, 255).astype(np.uint8)
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
# lower_yellow = np.array([7, 80, 0])
|
||||
# upper_yellow = np.array([32, 255, 182])
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_DILATE, kernel)
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# auto
|
||||
# R:31 M:v2 D:2.410110127692767
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
|
||||
# # 1. 增强饱和度(模糊照片需要更强的增强)
|
||||
# s = np.clip(s * 2.5, 0, 255).astype(np.uint8) # 从2.0改为2.5
|
||||
|
||||
# # 2. 增强亮度(模糊照片可能偏暗)
|
||||
# v = np.clip(v * 1.2, 0, 255).astype(np.uint8) # 新增:提升亮度
|
||||
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
|
||||
# # 3. 放宽HSV颜色范围(特别是模糊照片)
|
||||
# # 降低饱和度下限,提高亮度上限
|
||||
# lower_yellow = np.array([5, 50, 30]) # H:5-35, S:50-255, V:30-255
|
||||
# upper_yellow = np.array([35, 255, 255])
|
||||
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# # 4. 增强形态学操作(连接被分割的区域)
|
||||
# kernel_small = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
# kernel_large = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9)) # 更大的核
|
||||
|
||||
# # 先开运算去除噪声
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel_small)
|
||||
# # 多次膨胀连接区域(模糊照片需要更多膨胀)
|
||||
# mask = cv2.dilate(mask, kernel_large, iterations=2) # 增加迭代次数
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel_large) # 闭运算填充空洞
|
||||
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# area = cv2.contourArea(largest)
|
||||
# if area > 50:
|
||||
# # 5. 使用面积计算等效半径(更准确)
|
||||
# equivalent_radius = np.sqrt(area / np.pi)
|
||||
|
||||
# # 6. 同时使用minEnclosingCircle作为备选(取较大值)
|
||||
# (x, y), enclosing_radius = cv2.minEnclosingCircle(largest)
|
||||
|
||||
# # 取两者中的较大值,确保不遗漏
|
||||
# radius = max(equivalent_radius, enclosing_radius)
|
||||
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# codegee
|
||||
# R:24 M:v2 D:3.061493895819174
|
||||
# R:22 M:v2 D:3.3644971681267077 np.clip(s * 1.1, 0, 255)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 2. 调整饱和度策略:
|
||||
# 不要暴力翻倍,可以尝试稍微增强,或者使用 CLAHE 增强亮度/对比度
|
||||
# 这里我们稍微增加一点饱和度,并确保不溢出
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
# 对亮度通道 v 也可以做一点 CLAHE 处理来增强对比度(可选)
|
||||
# clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
|
||||
# v = clahe.apply(v)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 3. 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
# 降低 S 的下限 (80 -> 35),提高 V 的上限 (182 -> 255)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 4. 调整形态学操作
|
||||
# 去掉 MORPH_OPEN,因为它会减小面积。
|
||||
# 使用 MORPH_CLOSE (先膨胀后腐蚀) 来填充内部小黑洞,连接近邻区域
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
# 再进行一次膨胀,确保边缘被包含进来
|
||||
# mask = cv2.dilate(mask, kernel, iterations=1)
|
||||
|
||||
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
if contours:
|
||||
largest = max(contours, key=cv2.contourArea)
|
||||
|
||||
# 这里可以适当降低面积阈值,或者保持不变
|
||||
if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
|
||||
# --- 核心修改开始 ---
|
||||
# 1. 尝试拟合椭圆 (需要轮廓点至少为5个)
|
||||
if len(largest) >= 5:
|
||||
# 返回值: ((中心x, 中心y), (长轴, 短轴), 旋转角度)
|
||||
(x, y), (axes_major, axes_minor), angle = cv2.fitEllipse(largest)
|
||||
|
||||
# 2. 计算半径
|
||||
# 选项A:取长短轴的平均值 (比较稳健)
|
||||
# radius = (axes_major + axes_minor) / 4
|
||||
|
||||
# 选项B:直接取短轴的一半 (抗模糊最强,推荐)
|
||||
radius = axes_minor / 2
|
||||
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2_ellipse"
|
||||
else:
|
||||
# 如果点太少无法拟合椭圆,降级回 minEnclosingCircle
|
||||
(x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2"
|
||||
# --- 核心修改结束 ---
|
||||
|
||||
# 你的后续逻辑
|
||||
best_radius1 = radius * 5
|
||||
|
||||
# operas 4.5
|
||||
# R:25 M:v2 D:2.9554872521538527
|
||||
# hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
# h, s, v = cv2.split(hsv)
|
||||
|
||||
# # 1. 适度增强饱和度(不要过度,否则噪声也会增强)
|
||||
# s = np.clip(s * 1.5, 0, 255).astype(np.uint8)
|
||||
# hsv = cv2.merge((h, s, v))
|
||||
|
||||
# # 2. 放宽 HSV 阈值范围(关键改动)
|
||||
# # - 饱和度下限从 80 降到 40(捕捉淡黄色)
|
||||
# # - 亮度上限从 182 提高到 255(允许更亮的黄色)
|
||||
# lower_yellow = np.array([7, 40, 30])
|
||||
# upper_yellow = np.array([35, 255, 255])
|
||||
|
||||
# mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# # 3. 调整形态学操作:用 CLOSE 替代 OPEN
|
||||
# # CLOSE(先膨胀后腐蚀):填充内部空洞,连接相邻区域
|
||||
# # OPEN(先腐蚀后膨胀):会缩小区域,不适合模糊图像
|
||||
# kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (7, 7)) # 稍大的核
|
||||
# mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
# mask = cv2.dilate(mask, kernel, iterations=1) # 额外膨胀,确保边缘被包含
|
||||
|
||||
# contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
# if contours:
|
||||
# largest = max(contours, key=cv2.contourArea)
|
||||
# if cv2.contourArea(largest) > 50:
|
||||
# (x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
# best_center = (int(x), int(y))
|
||||
# best_radius = int(radius)
|
||||
# best_radius1 = radius * 5
|
||||
# method = "v2"
|
||||
|
||||
# # --- 新增:将 Mask 叠加到原图上用于调试 ---
|
||||
# # 创建一个彩色掩码(红色通道为255,其他为0)
|
||||
# mask_overlay = np.zeros_like(img_cv)
|
||||
# mask_overlay[:, :, 2] = mask # 将掩码放在红色通道 (BGR中的R)
|
||||
#
|
||||
# cv2.addWeighted(img_cv, 0.6, mask_overlay, 0.4, 0, img_cv)
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1
|
||||
|
||||
|
||||
def detect_circle_v2(frame):
|
||||
"""检测图像中的靶心(优先清晰轮廓,其次黄色区域)- 返回椭圆参数版本"""
|
||||
global REAL_RADIUS_CM
|
||||
img_cv = image.image2cv(frame, False, False)
|
||||
|
||||
best_center = best_radius = best_radius1 = method = None
|
||||
ellipse_params = None # 存储椭圆参数 ((x, y), (axes_major, axes_minor), angle)
|
||||
|
||||
# HSV 黄色掩码检测(模糊靶心)
|
||||
hsv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2HSV)
|
||||
h, s, v = cv2.split(hsv)
|
||||
|
||||
# 调整饱和度策略:稍微增强,不要过度
|
||||
s = np.clip(s * 1.1, 0, 255).astype(np.uint8)
|
||||
|
||||
hsv = cv2.merge((h, s, v))
|
||||
|
||||
# 放宽 HSV 阈值范围(针对模糊图像的关键调整)
|
||||
lower_yellow = np.array([7, 80, 0]) # 饱和度下限降低,捕捉淡黄色
|
||||
upper_yellow = np.array([32, 255, 255]) # 亮度上限拉满
|
||||
|
||||
mask = cv2.inRange(hsv, lower_yellow, upper_yellow)
|
||||
|
||||
# 调整形态学操作
|
||||
# 使用 MORPH_CLOSE (先膨胀后腐蚀) 来填充内部小黑洞,连接近邻区域
|
||||
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
|
||||
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
|
||||
|
||||
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
||||
|
||||
if contours:
|
||||
largest = max(contours, key=cv2.contourArea)
|
||||
|
||||
if cv2.contourArea(largest) > 50:
|
||||
# 尝试拟合椭圆 (需要轮廓点至少为5个)
|
||||
if len(largest) >= 5:
|
||||
# 返回值: ((中心x, 中心y), (width, height), 旋转角度)
|
||||
# 注意:width 和 height 是外接矩形的尺寸,不是长轴和短轴
|
||||
(x, y), (width, height), angle = cv2.fitEllipse(largest)
|
||||
|
||||
# 保存椭圆参数(保持原始顺序,用于绘制)
|
||||
ellipse_params = ((x, y), (width, height), angle)
|
||||
|
||||
# 计算半径:使用较小的尺寸作为短轴
|
||||
axes_minor = min(width, height)
|
||||
radius = axes_minor / 2
|
||||
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2_ellipse"
|
||||
else:
|
||||
# 如果点太少无法拟合椭圆,降级回 minEnclosingCircle
|
||||
(x, y), radius = cv2.minEnclosingCircle(largest)
|
||||
best_center = (int(x), int(y))
|
||||
best_radius = int(radius)
|
||||
method = "v2"
|
||||
ellipse_params = None # 圆形,没有椭圆参数
|
||||
|
||||
best_radius1 = radius * 5
|
||||
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
return result_img, best_center, best_radius, method, best_radius1, ellipse_params
|
||||
|
||||
|
||||
# ==================== 测试逻辑 ====================
|
||||
|
||||
def run_offline_test(image_path):
|
||||
"""读取图片,检测圆,绘制结果,保存图片"""
|
||||
|
||||
# 1. 检查文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 找不到图片文件: {image_path}")
|
||||
return
|
||||
|
||||
# 2. 使用 maix.image 读取图片 (适配 MaixPy v4)
|
||||
try:
|
||||
# 使用 image.load 读取文件,返回 Image 对象
|
||||
img = image.load(image_path)
|
||||
print(f"[INFO] 成功读取图片: {image_path} (尺寸: {img.width()}x{img.height()})")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 读取图片失败: {e}")
|
||||
print("提示:请确认 MaixPy 版本是否为 v4,且图片路径正确。")
|
||||
return
|
||||
|
||||
# 3. 调用 detect_circle_v2 函数
|
||||
print("[INFO] 正在调用 detect_circle_v2 进行检测...")
|
||||
start_time = time.ticks_ms()
|
||||
|
||||
result_img, center, radius, method, radius1, ellipse_params = detect_circle_v3(img)
|
||||
|
||||
cost_time = time.ticks_ms() - start_time
|
||||
print(f"[INFO] 检测完成,耗时: {cost_time}ms")
|
||||
print(f" 结果 -> 圆心: {center}, 半径: {radius}, 方法: {method}")
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
print(
|
||||
f" 椭圆 -> 中心: ({ell_center[0]:.1f}, {ell_center[1]:.1f}), 长轴: {max(width, height):.1f}, 短轴: {min(width, height):.1f}, 角度: {angle:.1f}°")
|
||||
|
||||
# 4. 绘制辅助线(可选,用于调试)
|
||||
if center and radius:
|
||||
# 为了绘制椭圆,需要转换回 cv2 图像
|
||||
img_cv = image.image2cv(result_img, False, False)
|
||||
|
||||
cx, cy = center
|
||||
|
||||
# 如果有椭圆参数,绘制椭圆
|
||||
if ellipse_params:
|
||||
(ell_center, (width, height), angle) = ellipse_params
|
||||
cx_ell, cy_ell = int(ell_center[0]), int(ell_center[1])
|
||||
|
||||
# 确定长轴和短轴
|
||||
if width >= height:
|
||||
# width 是长轴,height 是短轴
|
||||
axes_major = width
|
||||
axes_minor = height
|
||||
major_angle = angle # 长轴角度就是 angle
|
||||
minor_angle = angle + 90 # 短轴角度 = 长轴角度 + 90度
|
||||
else:
|
||||
# height 是长轴,width 是短轴
|
||||
axes_major = height
|
||||
axes_minor = width
|
||||
major_angle = angle + 90 # 长轴角度 = width角度 + 90度
|
||||
minor_angle = angle # 短轴角度就是 angle
|
||||
|
||||
# 使用 OpenCV 绘制椭圆(绿色,线宽2)
|
||||
cv2.ellipse(img_cv,
|
||||
(cx_ell, cy_ell), # 中心点
|
||||
(int(width / 2), int(height / 2)), # 半宽、半高
|
||||
angle, # 旋转角度(OpenCV需要原始angle)
|
||||
0, 360, # 起始和结束角度
|
||||
(0, 255, 0), # 绿色 (RGB格式)
|
||||
2) # 线宽
|
||||
|
||||
# 绘制椭圆中心点(红色)
|
||||
cv2.circle(img_cv, (cx_ell, cy_ell), 3, (255, 0, 0), -1)
|
||||
|
||||
import math
|
||||
# 绘制短轴(蓝色线条)
|
||||
minor_length = axes_minor / 2
|
||||
minor_angle_rad = math.radians(minor_angle)
|
||||
dx_minor = minor_length * math.cos(minor_angle_rad)
|
||||
dy_minor = minor_length * math.sin(minor_angle_rad)
|
||||
pt1_minor = (int(cx_ell - dx_minor), int(cy_ell - dy_minor))
|
||||
pt2_minor = (int(cx_ell + dx_minor), int(cy_ell + dy_minor))
|
||||
cv2.line(img_cv, pt1_minor, pt2_minor, (0, 0, 255), 2) # 蓝色 (RGB格式)
|
||||
else:
|
||||
# 如果没有椭圆参数,绘制圆形(红色)
|
||||
cv2.circle(img_cv, (cx, cy), radius, (0, 0, 255), 2)
|
||||
cv2.circle(img_cv, (cx, cy), 2, (0, 0, 255), -1)
|
||||
|
||||
# 转换回 maix image
|
||||
result_img = image.cv2image(img_cv, False, False)
|
||||
|
||||
# 定义颜色对象用于文字
|
||||
try:
|
||||
color_black = image.Color.from_rgb(0, 0, 0)
|
||||
except AttributeError:
|
||||
color_black = image.Color(0, 0, 0)
|
||||
|
||||
# D. 添加文字信息
|
||||
FOCAL_LENGTH_PIX = 1900
|
||||
d = (REAL_RADIUS_CM * FOCAL_LENGTH_PIX) / radius1 / 100.0
|
||||
info_str = f"R:{radius} M:{method} D:{d:.2f}"
|
||||
print(info_str)
|
||||
|
||||
# 计算文字位置,防止超出图片边界
|
||||
r_outer = int(radius * 11.0) if radius else 100
|
||||
text_y = cy - r_outer - 20 if cy > r_outer + 20 else cy + r_outer + 20
|
||||
|
||||
# 调用 draw_string
|
||||
result_img.draw_string(0, 0, info_str, color=color_black, scale=1.0)
|
||||
|
||||
# 5. 保存结果图片
|
||||
output_path = image_path.replace(".bmp", "_result.bmp")
|
||||
output_path = image_path.replace(".jpg", "_result.jpg")
|
||||
try:
|
||||
result_img.save(output_path, quality=100)
|
||||
print(f"[SUCCESS] 结果已保存至: {output_path}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 保存图片失败: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# ================= 配置区域 =================
|
||||
|
||||
# 1. 设置要测试的图片路径
|
||||
# 建议将图片放在与脚本同级目录,或者使用绝对路径
|
||||
TARGET_IMAGE = "/root/phot/None_314_258_0_0041.bmp"
|
||||
|
||||
TARGET_DIR = "/root/phot" # 修改为你想要读取的目录路径
|
||||
|
||||
# 支持的图片格式
|
||||
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.bmp']
|
||||
|
||||
# ================= 执行区域 =================
|
||||
if 'TARGET_DIR' in locals():
|
||||
# 读取目录下所有图片文件,过滤掉 _result.jpg 后缀的文件
|
||||
image_files = []
|
||||
if os.path.exists(TARGET_DIR) and os.path.isdir(TARGET_DIR):
|
||||
for filename in os.listdir(TARGET_DIR):
|
||||
# 检查文件扩展名
|
||||
if any(filename.lower().endswith(ext) for ext in IMAGE_EXTENSIONS):
|
||||
# 过滤掉 _result.jpg 后缀的文件
|
||||
if filename.endswith('no_target.jpg'):
|
||||
filepath = os.path.join(TARGET_DIR, filename)
|
||||
if os.path.isfile(filepath):
|
||||
image_files.append(filepath)
|
||||
|
||||
# 按文件名排序(可选)
|
||||
image_files.sort()
|
||||
|
||||
print(f"[INFO] 在目录 {TARGET_DIR} 中找到 {len(image_files)} 张图片")
|
||||
|
||||
# 处理每张图片
|
||||
for img_path in image_files:
|
||||
print(f"\n{'=' * 10} 开始处理: {img_path} {'=' * 10}")
|
||||
run_offline_test(img_path)
|
||||
else:
|
||||
print(f"[ERROR] 目录不存在或不是有效目录: {TARGET_DIR}")
|
||||
|
||||
else:
|
||||
run_offline_test(TARGET_IMAGE)
|
||||
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
# test_i2c_devices.py
|
||||
|
||||
import os
|
||||
from maix import i2c
|
||||
|
||||
def list_i2c_devices():
|
||||
"""List available I2C device nodes"""
|
||||
print("Available I2C devices:")
|
||||
|
||||
# Check /dev directory
|
||||
try:
|
||||
dev_files = os.listdir("/dev")
|
||||
i2c_devices = [f for f in dev_files if "i2c" in f]
|
||||
if i2c_devices:
|
||||
for dev in sorted(i2c_devices):
|
||||
print(f" /dev/{dev}")
|
||||
else:
|
||||
print(" No /dev/i2c-* devices found!")
|
||||
except Exception as e:
|
||||
print(f" Error listing /dev: {e}")
|
||||
|
||||
def try_i2c_bus(bus_num):
|
||||
"""Try to initialize an I2C bus"""
|
||||
try:
|
||||
bus = i2c.I2C(bus_num, i2c.Mode.MASTER)
|
||||
print(f" I2C bus {bus_num}: OK")
|
||||
return True
|
||||
except RuntimeError as e:
|
||||
print(f" I2C bus {bus_num}: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" I2C bus {bus_num}: Unexpected error: {e}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("I2C Device Diagnostic")
|
||||
print("=" * 60)
|
||||
|
||||
# List kernel devices
|
||||
list_i2c_devices()
|
||||
|
||||
# Try common bus numbers
|
||||
print("\nTesting I2C buses:")
|
||||
working_buses = []
|
||||
for bus_num in range(10):
|
||||
if try_i2c_bus(bus_num):
|
||||
working_buses.append(bus_num)
|
||||
|
||||
print(f"\nWorking buses: {working_buses}")
|
||||
|
||||
if not working_buses:
|
||||
print("\nERROR: No I2C buses available!")
|
||||
print("Possible causes:")
|
||||
print(" 1. I2C kernel driver not loaded")
|
||||
print(" 2. Device tree doesn't enable I2C")
|
||||
print(" 3. Different kernel version with different device naming")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
M01激光测距模块测试脚本 - 修正版
|
||||
基于文档中的完整命令示例
|
||||
"""
|
||||
|
||||
from maix import uart, pinmap, time
|
||||
import binascii
|
||||
|
||||
# ==================== 配置 ====================
|
||||
UART_PORT = "/dev/ttyS1"
|
||||
BAUDRATE = 9600
|
||||
|
||||
# 初始化串口
|
||||
try:
|
||||
pinmap.set_pin_function("A18", "UART1_RX")
|
||||
pinmap.set_pin_function("A19", "UART1_TX")
|
||||
laser_uart = uart.UART(UART_PORT, BAUDRATE)
|
||||
print("✅ 硬件初始化完成")
|
||||
except Exception as e:
|
||||
print(f"❌ 初始化失败: {e}")
|
||||
exit(1)
|
||||
|
||||
# ==================== 根据文档的完整命令集 ====================
|
||||
# 1. 激光开关(文档2.3.10,已验证可用)
|
||||
LASER_ON_CMD = bytes([0xAA, 0x00, 0x01, 0xBE, 0x00, 0x01, 0x00, 0x01, 0xC1])
|
||||
LASER_OFF_CMD = bytes([0xAA, 0x00, 0x01, 0xBE, 0x00, 0x01, 0x00, 0x00, 0xC0])
|
||||
|
||||
# 2. 尝试不同的测距命令格式
|
||||
TEST_COMMANDS = [
|
||||
# 格式1:文档2.3.12的单次测量(您测试失败的)
|
||||
{
|
||||
"name": "单次测量 (0x0020)",
|
||||
"cmd": bytes([0xAA, 0x00, 0x00, 0x20, 0x00, 0x01, 0x00, 0x00, 0x21]),
|
||||
"desc": "文档2.3.12 示例命令"
|
||||
},
|
||||
# 格式2:文档2.3.7的读取测量结果
|
||||
{
|
||||
"name": "读取测量结果 (0x0022)",
|
||||
"cmd": bytes([0xAA, 0x80, 0x00, 0x22, 0xA2]),
|
||||
"desc": "文档2.3.7 读取测量结果"
|
||||
},
|
||||
# 格式3:文档2.3.13的快速测量
|
||||
{
|
||||
"name": "快速测量 (0x0022带数据)",
|
||||
"cmd": bytes([0xAA, 0x00, 0x00, 0x22, 0x00, 0x01, 0x00, 0x00, 0x23]),
|
||||
"desc": "文档2.3.13 快速测量"
|
||||
},
|
||||
# 格式4:连续测量模式
|
||||
{
|
||||
"name": "连续测量模式 (0x0021)",
|
||||
"cmd": bytes([0xAA, 0x00, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x22]),
|
||||
"desc": "文档2.3.14 连续测量"
|
||||
}
|
||||
]
|
||||
|
||||
def clear_buffer():
|
||||
"""清空串口缓冲区"""
|
||||
try:
|
||||
data = laser_uart.read(-1)
|
||||
if data:
|
||||
print(f"清空: {len(data)}字节")
|
||||
except:
|
||||
pass
|
||||
|
||||
def send_and_wait(cmd, name, wait_time=2000):
|
||||
"""发送命令并等待响应"""
|
||||
print(f"\n📤 发送: {name}")
|
||||
print(f" 命令: {cmd.hex()}")
|
||||
|
||||
clear_buffer()
|
||||
|
||||
try:
|
||||
laser_uart.write(cmd)
|
||||
print(f" 已发送 {len(cmd)} 字节")
|
||||
except Exception as e:
|
||||
print(f" ❌ 发送失败: {e}")
|
||||
return None
|
||||
|
||||
# 等待响应
|
||||
start_time = time.ticks_ms()
|
||||
response = b""
|
||||
|
||||
while time.ticks_ms() - start_time < wait_time:
|
||||
try:
|
||||
chunk = laser_uart.read(1)
|
||||
if chunk:
|
||||
response += chunk
|
||||
# 完整响应通常是9或13字节
|
||||
if len(response) >= 9:
|
||||
# 检查是否完整帧
|
||||
if response[0] in [0xAA, 0xEE]:
|
||||
if len(response) >= 13: # 测距完整响应
|
||||
break
|
||||
elif response[0] == 0xEE: # 错误响应
|
||||
break
|
||||
except:
|
||||
break
|
||||
|
||||
time.sleep_ms(10)
|
||||
|
||||
if response:
|
||||
print(f" 📥 响应: {response.hex()}")
|
||||
print(f" 长度: {len(response)} 字节")
|
||||
|
||||
# 解析错误码
|
||||
if response[0] == 0xEE and len(response) >= 9:
|
||||
err_code = (response[7] << 8) | response[8]
|
||||
error_mapping = {
|
||||
0x0000: "无错误",
|
||||
0x0001: "硬件错误",
|
||||
0x0002: "无输出数据",
|
||||
0x0003: "反射信号太弱",
|
||||
0x0004: "反射信号太强",
|
||||
0x0005: "温度太高(>40℃)",
|
||||
0x0006: "温度太低(<-10℃)",
|
||||
0x0007: "电源电压低(<2.5V)",
|
||||
0x0008: "超出量程",
|
||||
0x0009: "读通讯错误",
|
||||
0x000A: "写通讯错误",
|
||||
0x000B: "地址错误"
|
||||
}
|
||||
err_msg = error_mapping.get(err_code, f"未知错误: 0x{err_code:04X}")
|
||||
print(f" ❌ 模块错误: {err_msg}")
|
||||
else:
|
||||
print(" ⚠️ 无响应")
|
||||
|
||||
return response
|
||||
|
||||
def parse_distance_data(response):
|
||||
"""解析距离数据"""
|
||||
if not response or len(response) < 13:
|
||||
return None
|
||||
|
||||
if response[0] != 0xAA or response[3] not in [0x20, 0x21, 0x22]:
|
||||
return None
|
||||
|
||||
# 解析4字节BCD码
|
||||
bcd_bytes = response[6:10]
|
||||
distance_int = 0
|
||||
|
||||
for byte in bcd_bytes:
|
||||
high = (byte >> 4) & 0x0F
|
||||
low = byte & 0x0F
|
||||
|
||||
if high > 9 or low > 9:
|
||||
return None
|
||||
|
||||
distance_int = distance_int * 100 + high * 10 + low
|
||||
|
||||
distance_m = distance_int / 1000.0
|
||||
|
||||
# 信号质量
|
||||
signal = 0
|
||||
if len(response) >= 12:
|
||||
signal = (response[10] << 8) | response[11]
|
||||
|
||||
return {
|
||||
'meters': distance_m,
|
||||
'millimeters': distance_m * 1000,
|
||||
'signal': signal,
|
||||
'raw': response.hex()
|
||||
}
|
||||
|
||||
# ==================== 主测试 ====================
|
||||
print("\n" + "="*50)
|
||||
print("M01激光测距模块详细测试")
|
||||
print("="*50)
|
||||
|
||||
try:
|
||||
# 1. 测试基本连接
|
||||
print("\n1. 测试模块连接...")
|
||||
version_cmd = bytes([0xAA, 0x80, 0x00, 0x0A, 0x8A])
|
||||
resp = send_and_wait(version_cmd, "读取硬件版本")
|
||||
|
||||
if resp and resp[0] == 0xAA and resp[3] == 0x0A:
|
||||
print(f"✅ 模块正常,版本: {resp[6]:02X}{resp[7]:02X}")
|
||||
else:
|
||||
print("❌ 模块连接测试失败")
|
||||
exit(1)
|
||||
|
||||
# 2. 开启激光
|
||||
print("\n2. 开启激光...")
|
||||
resp = send_and_wait(LASER_ON_CMD, "开启激光", 1000)
|
||||
if resp and resp.hex() == "aa0001be00010001c1":
|
||||
print("✅ 激光已开启")
|
||||
|
||||
print(" 等待激光稳定...")
|
||||
time.sleep(2) # 重要等待时间
|
||||
|
||||
# 3. 尝试不同的测距命令
|
||||
print("\n3. 测试不同测距命令...")
|
||||
|
||||
for i, test_cmd in enumerate(TEST_COMMANDS):
|
||||
print(f"\n{'='*30}")
|
||||
print(f"测试 {i+1}: {test_cmd['name']}")
|
||||
print(f"{test_cmd['desc']}")
|
||||
print(f"{'='*30}")
|
||||
|
||||
resp = send_and_wait(test_cmd['cmd'], test_cmd['name'], 3000)
|
||||
|
||||
if resp:
|
||||
if resp[0] == 0xAA and len(resp) >= 13:
|
||||
result = parse_distance_data(resp)
|
||||
if result:
|
||||
print(f"✅ 测距成功!")
|
||||
print(f" 距离: {result['meters']:.3f} m")
|
||||
print(f" 距离: {result['millimeters']:.1f} mm")
|
||||
print(f" 信号质量: {result['signal']}")
|
||||
break
|
||||
else:
|
||||
print("❌ 无法解析距离数据")
|
||||
elif resp[0] == 0xEE:
|
||||
print("❌ 命令执行错误")
|
||||
else:
|
||||
print("❌ 无效响应格式")
|
||||
else:
|
||||
print("❌ 无响应")
|
||||
|
||||
time.sleep(1) # 命令间间隔
|
||||
|
||||
# 4. 关闭激光
|
||||
print("\n4. 关闭激光...")
|
||||
send_and_wait(LASER_OFF_CMD, "关闭激光", 1000)
|
||||
|
||||
print("\n" + "="*50)
|
||||
print("🏁 测试完成")
|
||||
print("="*50)
|
||||
|
||||
print("\n📋 测试总结:")
|
||||
print("1. 模块通信: ✅ 正常")
|
||||
print("2. 激光控制: ✅ 正常")
|
||||
print("3. 测距功能: ❌ 有问题")
|
||||
print("\n建议:")
|
||||
print("1. 检查激光是否实际发光(在暗处观察红点)")
|
||||
print("2. 确保测量目标在有效范围内(0.2-60米)")
|
||||
print("3. 确保目标有足够反射率(白色平面最佳)")
|
||||
print("4. 如果所有测距命令都返回ERR_ADDR,可能是固件版本问题")
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n🛑 用户中断")
|
||||
laser_uart.write(LASER_OFF_CMD)
|
||||
print("✅ 已发送关闭指令")
|
||||
except Exception as e:
|
||||
print(f"\n❌ 测试出错: {e}")
|
||||
@@ -0,0 +1,16 @@
|
||||
from maix import gpio, pinmap, time
|
||||
|
||||
|
||||
#设置引脚为输出
|
||||
led = gpio.GPIO("A25", gpio.Mode.OUT)
|
||||
#设置低电平
|
||||
led.value(0)
|
||||
|
||||
while 1:
|
||||
# time.sleep_ms(1000)
|
||||
#对该引脚的电平进行取反(原高-》现低)
|
||||
# led.toggle()
|
||||
led.value(1)
|
||||
#延时
|
||||
time.sleep_ms(5000)
|
||||
led.value(0)
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Read the digital voltage level on the MaixCAM P21 pin.
|
||||
|
||||
P21 is a digital GPIO pin, not the MaixCAM analog ADC input. Therefore this
|
||||
script can only distinguish LOW and HIGH. For a continuous voltage value,
|
||||
connect the signal to the board's B3/ADC pin and use ADC channel 0 instead.
|
||||
|
||||
Do not apply more than 3.3 V to P21. Always connect the signal ground to the
|
||||
MaixCAM ground.
|
||||
"""
|
||||
|
||||
from maix import app, gpio, pinmap, time
|
||||
|
||||
|
||||
PIN = "P21"
|
||||
IO_HIGH_VOLTAGE = 3.3
|
||||
SAMPLE_INTERVAL_MS = 200
|
||||
|
||||
|
||||
def find_gpio_function(pin):
|
||||
"""Return the GPIO function supported by the requested physical pin."""
|
||||
functions = pinmap.get_pin_functions(pin)
|
||||
gpio_functions = [name for name in functions if name.startswith("GPIO")]
|
||||
|
||||
print(f"{pin} supported functions: {', '.join(functions)}")
|
||||
if not gpio_functions:
|
||||
raise RuntimeError(f"{pin} does not provide a GPIO input function")
|
||||
|
||||
return gpio_functions[0]
|
||||
|
||||
|
||||
def main():
|
||||
gpio_function = find_gpio_function(PIN)
|
||||
pinmap.set_pin_function(PIN, gpio_function)
|
||||
voltage_input = gpio.GPIO(gpio_function, gpio.Mode.IN)
|
||||
|
||||
print(f"Reading {PIN} through {gpio_function}")
|
||||
print("P21 only reports LOW/HIGH; displayed voltage is an estimate.")
|
||||
print("Press the MaixCAM exit key to stop.")
|
||||
|
||||
while not app.need_exit():
|
||||
level = voltage_input.value()
|
||||
estimated_voltage = IO_HIGH_VOLTAGE if level else 0.0
|
||||
state = "HIGH" if level else "LOW"
|
||||
print(
|
||||
f"{PIN}: level={level}, state={state}, "
|
||||
f"estimated_voltage={estimated_voltage:.1f} V"
|
||||
)
|
||||
time.sleep_ms(SAMPLE_INTERVAL_MS)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print(f"P21 voltage detection failed: {error}")
|
||||
print("Check that this MaixCAM model exposes P21 as a GPIO pin.")
|
||||
raise
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
# test_power_with_init.py
|
||||
|
||||
from maix import i2c, time
|
||||
import sys
|
||||
|
||||
# INA226 register addresses
|
||||
INA226_ADDR = 0x40
|
||||
REG_CONFIGURATION = 0x00
|
||||
REG_BUS_VOLTAGE = 0x02
|
||||
REG_CURRENT = 0x04
|
||||
REG_CALIBRATION = 0x05
|
||||
|
||||
# Configuration values
|
||||
CONFIG_VALUE = 0x4527 # Configuration: 16 averages, 1.1ms conversion time, continuous mode
|
||||
CALIBRATION_VALUE = 0x1400 # Calibration value
|
||||
|
||||
def write_register(bus, reg, value):
|
||||
"""Write to INA226 register"""
|
||||
data = [(value >> 8) & 0xFF, value & 0xFF]
|
||||
bus.writeto_mem(INA226_ADDR, reg, bytes(data))
|
||||
|
||||
def read_register(bus, reg):
|
||||
"""Read from INA226 register"""
|
||||
data = bus.readfrom_mem(INA226_ADDR, reg, 2)
|
||||
return (data[0] << 8) | data[1]
|
||||
|
||||
def init_ina226(bus):
|
||||
"""Initialize INA226 chip"""
|
||||
try:
|
||||
# Write configuration register
|
||||
write_register(bus, REG_CONFIGURATION, CONFIG_VALUE)
|
||||
time.sleep_ms(10)
|
||||
|
||||
# Write calibration register
|
||||
write_register(bus, REG_CALIBRATION, CALIBRATION_VALUE)
|
||||
time.sleep_ms(10)
|
||||
|
||||
# Verify configuration by reading it back
|
||||
config_read = read_register(bus, REG_CONFIGURATION)
|
||||
if config_read != CONFIG_VALUE:
|
||||
print(f" Warning: Config readback mismatch: 0x{config_read:04X} != 0x{CONFIG_VALUE:04X}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f" Init failed: {e}")
|
||||
return False
|
||||
|
||||
def read_voltage(bus):
|
||||
"""Read bus voltage"""
|
||||
raw = read_register(bus, REG_BUS_VOLTAGE)
|
||||
voltage = raw * 1.25 / 1000
|
||||
return voltage
|
||||
|
||||
def read_current(bus):
|
||||
"""Read current"""
|
||||
raw = read_register(bus, REG_CURRENT)
|
||||
# Handle signed value
|
||||
if raw & 0x8000:
|
||||
raw = raw - 0x10000
|
||||
current_lsb = 0.001 * CALIBRATION_VALUE / 4096
|
||||
current = raw * current_lsb * 1000 # mA
|
||||
return current
|
||||
|
||||
def test_i2c_bus(bus_num):
|
||||
"""Test a single I2C bus with full initialization"""
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Testing I2C Bus {bus_num}")
|
||||
print(f"{'='*60}")
|
||||
|
||||
try:
|
||||
# Step 1: Initialize I2C bus
|
||||
print(f" 1. Initializing I2C bus...")
|
||||
bus = i2c.I2C(bus_num, i2c.Mode.MASTER)
|
||||
print(f" OK")
|
||||
|
||||
# Step 2: Initialize INA226
|
||||
print(f" 2. Initializing INA226...")
|
||||
if not init_ina226(bus):
|
||||
print(f" FAILED")
|
||||
return False
|
||||
print(f" OK")
|
||||
|
||||
# Step 3: Read voltage multiple times
|
||||
print(f" 3. Reading voltage...")
|
||||
for i in range(5):
|
||||
try:
|
||||
voltage = read_voltage(bus)
|
||||
current = read_current(bus)
|
||||
print(f" Read {i+1}: {voltage:.3f}V, {current:.1f}mA")
|
||||
time.sleep_ms(100)
|
||||
except Exception as e:
|
||||
print(f" Read {i+1} failed: {e}")
|
||||
|
||||
print(f" SUCCESS")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f" FAILED: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""Test all I2C buses"""
|
||||
print("INA226 Test with Proper Initialization")
|
||||
print("=" * 60)
|
||||
|
||||
# Test buses in order of likelihood
|
||||
test_order = [5, 1, 3, 4, 0, 2]
|
||||
|
||||
success_buses = []
|
||||
|
||||
for bus_num in test_order:
|
||||
if test_i2c_bus(bus_num):
|
||||
success_buses.append(bus_num)
|
||||
# If we found a working bus, stop testing others
|
||||
break
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"Summary:")
|
||||
print(f" Working buses: {success_buses}")
|
||||
if not success_buses:
|
||||
print(f" ERROR: No working I2C bus found!")
|
||||
return 1
|
||||
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,139 @@
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
import unittest
|
||||
|
||||
|
||||
class _FakeTime:
|
||||
@staticmethod
|
||||
def sleep(_seconds):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def sleep_ms(_milliseconds):
|
||||
pass
|
||||
|
||||
@staticmethod
|
||||
def ticks_ms():
|
||||
return 0
|
||||
|
||||
@staticmethod
|
||||
def ticks_diff(left, right):
|
||||
return left - right
|
||||
|
||||
|
||||
class _FakeLogger:
|
||||
def debug(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def info(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def warning(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def error(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
|
||||
class _FakeSocket:
|
||||
def __init__(self, recv_data=b""):
|
||||
self.recv_data = recv_data
|
||||
self.closed = False
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
def recv(self, _size, *_flags):
|
||||
return self.recv_data
|
||||
|
||||
|
||||
class _StopAfterCallback:
|
||||
def __init__(self):
|
||||
self.stopped = False
|
||||
|
||||
def is_set(self):
|
||||
return self.stopped
|
||||
|
||||
|
||||
maix_module = types.ModuleType("maix")
|
||||
maix_module.time = _FakeTime
|
||||
maix_module.network = types.SimpleNamespace()
|
||||
maix_module.err = types.SimpleNamespace()
|
||||
sys.modules.setdefault("maix", maix_module)
|
||||
sys.modules.setdefault("ujson", json)
|
||||
|
||||
netcore_module = types.ModuleType("archery_netcore")
|
||||
netcore_module.get_config = lambda: {"SERVER_IP": "127.0.0.1", "SERVER_PORT": 1234}
|
||||
netcore_module.parse_packet = lambda _packet: (0, {})
|
||||
netcore_module.make_packet = lambda *_args, **_kwargs: b""
|
||||
netcore_module.actions_for_inner_cmd = lambda *_args, **_kwargs: []
|
||||
sys.modules["archery_netcore"] = netcore_module
|
||||
|
||||
hardware_module = types.ModuleType("hardware")
|
||||
hardware_module.hardware_manager = types.SimpleNamespace()
|
||||
sys.modules["hardware"] = hardware_module
|
||||
|
||||
power_module = types.ModuleType("power")
|
||||
power_module.get_bus_voltage = lambda: 0
|
||||
power_module.voltage_to_percent = lambda _voltage: 0
|
||||
sys.modules["power"] = power_module
|
||||
|
||||
import logger_manager
|
||||
import wifi
|
||||
import network
|
||||
|
||||
|
||||
class WiFiFailoverTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
logger_manager.logger_manager._logger = _FakeLogger()
|
||||
|
||||
def test_monitor_switches_when_sta_association_is_lost(self):
|
||||
manager = wifi.wifi_manager
|
||||
stop_event = _StopAfterCallback()
|
||||
callbacks = []
|
||||
|
||||
manager._wifi_socket = _FakeSocket()
|
||||
manager._wifi_quality_stop_event = stop_event
|
||||
manager._network_type_callback = lambda: "wifi"
|
||||
manager.is_sta_associated = lambda: False
|
||||
manager._get_wifi_rssi_dbm = lambda: None
|
||||
|
||||
def on_poor_quality():
|
||||
callbacks.append(True)
|
||||
stop_event.stopped = True
|
||||
|
||||
manager._on_poor_quality_callback = on_poor_quality
|
||||
manager._quality_monitor_loop()
|
||||
|
||||
self.assertEqual(callbacks, [True])
|
||||
self.assertIsNone(manager.last_wifi_rtt_ms)
|
||||
|
||||
def test_tls_connection_check_rejects_lost_sta_association(self):
|
||||
manager = network.network_manager
|
||||
sock = _FakeSocket()
|
||||
wifi.wifi_manager._wifi_socket = sock
|
||||
wifi.wifi_manager._wifi_connected = True
|
||||
wifi.wifi_manager._wifi_ip = "192.168.1.2"
|
||||
wifi.wifi_manager.is_sta_associated = lambda: False
|
||||
manager._tcp_connected = True
|
||||
|
||||
self.assertFalse(manager._check_wifi_connection())
|
||||
self.assertTrue(sock.closed)
|
||||
self.assertIsNone(wifi.wifi_manager.wifi_socket)
|
||||
self.assertFalse(manager.tcp_connected)
|
||||
|
||||
def test_receive_eof_marks_wifi_tcp_disconnected(self):
|
||||
manager = network.network_manager
|
||||
sock = _FakeSocket(recv_data=b"")
|
||||
wifi.wifi_manager._wifi_socket = sock
|
||||
manager._tcp_connected = True
|
||||
|
||||
self.assertEqual(manager.receive_tcp_data_via_wifi(), b"")
|
||||
self.assertTrue(sock.closed)
|
||||
self.assertIsNone(wifi.wifi_manager.wifi_socket)
|
||||
self.assertFalse(manager.tcp_connected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user