logo

OpenMV4 H7 Plus 运行卡死、USB断连且无法重连(固件5.0.0)

2026-07-25 17:04
J
j7r6j9lehpio

OpenMV4 H7 Plus 运行卡死、USB断连且无法重连(固件5.0.0)

问题概述

OpenMV4 H7 Plus 在运行复杂视觉识别代码时频繁卡死:程序无响应、IDE无法强制退出,数秒后自动断开连接;此后 USB 完全失联(设备管理器显示 Unknown device),必须重新刷写固件才能恢复。已复现于固件 v5.0.0。

关键现象

  • 运行中突然卡死,IDE 点击“Stop”无反应,等待约 5–10 秒后自动断开连接
  • 断连后立即尝试“Connect”无任何响应,稍等后弹出 “Failed to open port” 错误窗口
  • 后续 IDE 无法识别设备,设备管理器显示黄色感叹号的 “Unknown device”,需手动重刷固件才可恢复
  • 故障在执行含 CSI 摄像头 + 多重形状/颜色识别 + UART 通信的复杂循环时稳定触发

硬件与环境信息

  • 硬件型号:OpenMV4 H7 Plus(正/反面实拍图见下方)
  • 固件版本:5.0.0(IDE 底部确认)
  • 参考教程:[颜色形状同时识别 · OpenMV中文入门教程](https://book.openmv.cc/image/blob_circle.html)

故障代码(精简关键段)

import csi
import gc
import math
import time
from pyb import UART

# ...(省略中间配置)...

csi0 = csi.CSI()
csi0.reset()
csi0.pixformat(csi.RGB565)
csi0.framesize(csi.QVGA)
csi0.snapshot(time=2000)
csi0.auto_gain(False)
csi0.auto_whitebal(False)

uart = UART(UART_ID, UART_BAUDRATE, timeout_char=200)
clock = time.clock()

while True:
    clock.tick()
    img = csi0.snapshot()  # ← 卡死高发点
    target = detect_shape_command(img)  # ← 含 find_blobs / find_rects / find_circles 复合调用
    # ... UART 发送 & draw_status ...
    if frame_count >= GC_PERIOD_FRAMES:
        gc.collect()  # ← 已启用但未缓解
        frame_count = 0

相关截图

image
image
image
image

设备实物图

image
image
J
j7r6j9lehpio

现在降低分辨率后会好一些,但是担心之后无法支持识别二维码

image.png
J
j7r6j9lehpio

OpenMV4 H7 Plus vision front-end.

Goal for this stage:

1. Keep live camera preview running.

2. Recognize single red/yellow/green circle/square/triangle commands.

3. Send a unified ASCII command frame to the waveform generator controller.

Wiring for UART3 on OpenMV4 H7 Plus:

P4 = TX, P5 = RX, GND must be shared with the waveform generator controller.

import csi import gc import math import time from pyb import UART

UART_ID = 3 UART_BAUDRATE = 115200 SEND_PERIOD_MS = 500 DEBUG_USB_PRINT = False FULL_DEBUG_OVERLAY = False

FRAME_VERSION = "OMV1"

WAVE_NONE = "NONE" WAVE_SIN = "SIN" WAVE_SQUARE = "SQUARE" WAVE_TRI = "TRI" MODE_IMAGE = "IMG" SOURCE_SHAPE = "SHAPE" STATUS_VALID = "VALID" STATUS_NO_TARGET = "NO_TARGET"

LAB thresholds under normal indoor light. If the target is not stable, tune

these tuples with OpenMV IDE: Tools -> Machine Vision -> Threshold Editor.

COLOR_RULES = [ { "name": "RED", "threshold": (30, 100, 18, 127, 8, 127), "draw_color": (255, 0, 0), "freq_hz": 100, "amp_mvpp": 10000, }, { "name": "YELLOW", "threshold": (0, 100, -20, 25, 36, 127), "draw_color": (255, 255, 0), "freq_hz": 1000, "amp_mvpp": 1000, }, { "name": "GREEN", "threshold": (0, 100, -47, -2, 13, 65), "draw_color": (0, 255, 0), "freq_hz": 10000, "amp_mvpp": 100, }, ]

SHAPE_RULES = { "CIRCLE": {"wave": WAVE_SIN}, "SQUARE": {"wave": WAVE_SQUARE}, "TRIANGLE": {"wave": WAVE_TRI}, }

MIN_BLOB_PIXELS = 450 MIN_BLOB_AREA = 600 MIN_BLOB_PIXELS_QQVGA = 120 MIN_BLOB_AREA_QQVGA = 160 BLOB_X_STRIDE = 2 BLOB_Y_STRIDE = 2 MAX_SHAPE_CANDIDATES = 3 GC_PERIOD_FRAMES = 30

Shape method name shown here and in the final notes:

OpenMV native ROI detectors with blob fallback.

This follows OpenMV official examples:

find_rects() for rotated rectangles, find_circles() for circles, and

find_blobs() geometry only as the final triangle fallback.

SHAPE_METHOD_NAME = "OPENMV_NATIVE_ROI_DETECTORS"

ROI_MARGIN = 8

RECT_THRESHOLD = 10000 RECT_CENTER_TOLERANCE_RATIO = 0.30 RECT_AREA_RATIO_MIN = 0.45 RECT_AREA_RATIO_MAX = 1.80 RECT_FILL_MIN = 0.55 RECT_SIDE_RATIO_MAX = 1.75 MIN_QUAD_FILL_MIN = 0.76 MIN_QUAD_SIDE_RATIO_MAX = 1.85

CIRCLE_THRESHOLD = 2000 CIRCLE_MARGIN = 10 CIRCLE_R_STEP = 4 CIRCLE_CENTER_TOLERANCE_RATIO = 0.28 CIRCLE_RADIUS_MIN_RATIO = 0.32 CIRCLE_RADIUS_MAX_RATIO = 0.62 CIRCLE_FILL_MIN = 0.58 CIRCLE_FILL_MAX = 0.90 CIRCLE_BBOX_FILL_MIN = 0.69 CIRCLE_BBOX_FILL_MAX = 0.84 CIRCLE_CIRCULARITY_GUARD_MIN = 0.58 CIRCLE_BBOX_ASPECT_MAX = 1.25 STRONG_SQUARE_QUAD_FILL_MIN = 0.88

TRIANGLE_DENSITY_MAX = 0.68 TRIANGLE_FILL_MAX = 0.62 CIRCLE_LIKE_FILL_MIN = 0.70 SQUARE_LIKE_FILL_MIN = 0.72

COLOR_CENTER_ROI_DIV = 4 COLOR_CENTER_ROI_MIN = 10

COLOR_PROFILES = { "RED": {"a": 72.5, "b": 67.5, "a_scale": 55.0, "b_scale": 60.0}, "YELLOW": {"a": 2.5, "b": 81.5, "a_scale": 45.0, "b_scale": 45.0}, "GREEN": {"a": -24.5, "b": 39.0, "a_scale": 24.0, "b_scale": 28.0}, }

def clamp_int(value, lo, hi): if value < lo: return lo if value > hi: return hi return value

def checksum_xor(text): checksum = 0 for ch in text: checksum ^= ord(ch) return "%02X" % (checksum & 0xFF)

def build_frame(seq, result): body = "%s,%d,%s,%s,%s,%d,%d,%d,%d,%s,%s" % ( FRAME_VERSION, seq, result["mode"], result["source"], result["wave"], result["freq_hz"], result["amp_mvpp"], result["sweep_pct"], result["enable"], result["compose"], result["status"], ) return "$%s*%s\r\n" % (body, checksum_xor(body))

def draw_status(img, result, fps, tx_count, target): if FULL_DEBUG_OVERLAY: img.draw_string((4, 4), "OpenMV4 H7 Plus", color=(255, 255, 255), scale=1) img.draw_string((4, 18), "MODE: %s" % result["mode"], color=(0, 255, 255), scale=1) img.draw_string((4, 32), "SRC : %s" % result["source"], color=(0, 255, 255), scale=1) img.draw_string((4, 46), "WAVE: %s" % result["wave"], color=(255, 255, 0), scale=1) img.draw_string( (4, 60), "F=%dHz A=%dmVpp" % (result["freq_hz"], result["amp_mvpp"]), color=(255, 255, 0), scale=1, ) img.draw_string( (4, 74), "SWEEP=%d%% EN=%d" % (result["sweep_pct"], result["enable"]), color=(255, 255, 0), scale=1, ) img.draw_string((4, 88), "TX=%d FPS=%.1f" % (tx_count, fps), color=(0, 255, 0), scale=1) target_y = 102 debug_y = 116 else: img.draw_string((2, 2), "%s" % result["source"], color=(0, 255, 255), scale=1) img.draw_string((2, 16), "W:%s FPS:%.1f" % (result["wave"], fps), color=(255, 255, 0), scale=1) target_y = 30 debug_y = 44

if target:
    img.draw_string(
        (4, target_y),
        "%s_%s x=%d y=%d" % (
            target["color_name"],
            target["shape_name"],
            target["blob"].cx,
            target["blob"].cy,
        ),
        color=(0, 255, 0),
        scale=1,
    )
    if FULL_DEBUG_OVERLAY:
        img.draw_string(
            (4, debug_y),
            "RS=%d CS=%d D=%.2f F=%.2f" % (
                target["features"]["rect_score"],
                target["features"]["circle_score"],
                target["features"]["density"],
                target["features"]["fill_ratio"],
            ),
            color=(0, 255, 0),
            scale=1,
        )
else:
    img.draw_string((4, target_y), "NO_TARGET", color=(255, 80, 80), scale=1)

def make_no_target_result(): return { "mode": MODE_IMAGE, "source": SOURCE_SHAPE, "wave": WAVE_NONE, "freq_hz": 0, "amp_mvpp": 0, "sweep_pct": 0, "enable": 0, "compose": "NONE", "status": STATUS_NO_TARGET, }

def make_target_result(target): return { "mode": MODE_IMAGE, "source": target["source"], "wave": target["wave"], "freq_hz": target["freq_hz"], "amp_mvpp": target["amp_mvpp"], "sweep_pct": 0, "enable": 1, "compose": "NONE", "status": STATUS_VALID, }

def normalize_result(result): result["freq_hz"] = clamp_int(result["freq_hz"], 0, 20000000) result["amp_mvpp"] = clamp_int(result["amp_mvpp"], 0, 10000) result["sweep_pct"] = clamp_int(result["sweep_pct"], 0, 100) result["enable"] = 1 if result["enable"] else 0 return result

def safe_feature(obj, name, default=0): try: value = getattr(obj, name) if callable(value): value = value() return value except Exception: return default

def image_size(img): return safe_feature(img, "width", 320), safe_feature(img, "height", 240)

def expanded_roi(img, blob, margin): img_w, img_h = image_size(img) x = max(0, blob.x - margin) y = max(0, blob.y - margin) x2 = min(img_w, blob.x + blob.w + margin) y2 = min(img_h, blob.y + blob.h + margin) return (x, y, max(1, x2 - x), max(1, y2 - y))

def point_distance2(x1, y1, x2, y2): dx = x1 - x2 dy = y1 - y2 return (dx dx) + (dy dy)

def circularity_from_blob(blob): perimeter = safe_feature(blob, "perimeter", 0) pixels = safe_feature(blob, "pixels", 0) if perimeter <= 0: return 0 return (4.0 math.pi pixels) / (perimeter * perimeter)

def polygon_side_ratio(vertices): if len(vertices) < 3: return 999.0

lengths = []
for idx in range(len(vertices)):
    x1, y1 = vertices[idx]
    x2, y2 = vertices[(idx + 1) % len(vertices)]
    lengths.append(math.sqrt(point_distance2(x1, y1, x2, y2)))

shortest = min(lengths)
longest = max(lengths)
if shortest <= 0:
    return 999.0
return longest / shortest

def polygon_area(points): if len(points) < 3: return 0

area2 = 0
for idx in range(len(points)):
    x1, y1 = points[idx]
    x2, y2 = points[(idx + 1) % len(points)]
    area2 += (x1 * y2) - (x2 * y1)
if area2 < 0:
    area2 = -area2
return area2 / 2

def rect_tuple(rect): value = safe_feature(rect, "rect", None) if value: return value return ( safe_feature(rect, "x", 0), safe_feature(rect, "y", 0), safe_feature(rect, "w", 0), safe_feature(rect, "h", 0), )

def corners_list(rect): corners = safe_feature(rect, "corners", []) if not corners: return [] return list(corners)

def min_corners_list(blob): corners = safe_feature(blob, "min_corners", []) if not corners: return [] return list(corners)

def circle_tuple(circle): return ( safe_feature(circle, "x", 0), safe_feature(circle, "y", 0), safe_feature(circle, "r", 0), safe_feature(circle, "magnitude", 0), )

def normalize_point_to_image(x, y, roi, blob): if point_distance2(x, y, blob.cx, blob.cy) <= point_distance2(x + roi[0], y + roi[1], blob.cx, blob.cy): return x, y return x + roi[0], y + roi[1]

def blob_fill_ratio(blob): area = max(1, blob.w * blob.h) return safe_feature(blob, "pixels", 0) / area

def bbox_aspect_ratio(blob): shortest = min(blob.w, blob.h) longest = max(blob.w, blob.h) if shortest <= 0: return 999.0 return longest / shortest

def blob_score(blob): return safe_feature(blob, "pixels", blob.w * blob.h)

def color_rule_by_name(name): for color_rule in COLOR_RULES: if color_rule["name"] == name: return color_rule return None

def center_roi(img, blob): img_w, img_h = image_size(img) size = max(COLOR_CENTER_ROI_MIN, min(blob.w, blob.h) // COLOR_CENTER_ROI_DIV) x = clamp_int(blob.cx - (size // 2), 0, max(0, img_w - size)) y = clamp_int(blob.cy - (size // 2), 0, max(0, img_h - size)) return (x, y, size, size)

def color_profile_distance(stats, profile): a_mean = safe_feature(stats, "a_mean", 0) b_mean = safe_feature(stats, "b_mean", 0) da = (a_mean - profile["a"]) / profile["a_scale"] db = (b_mean - profile["b"]) / profile["b_scale"] return (da da) + (db db)

def refine_color_rule(img, blob, fallback_rule): try: stats = img.get_statistics(roi=center_roi(img, blob)) except Exception: return fallback_rule

best_name = fallback_rule["name"]
best_score = 999999.0
for name, profile in COLOR_PROFILES.items():
    score = color_profile_distance(stats, profile)
    if score < best_score:
        best_score = score
        best_name = name

refined = color_rule_by_name(best_name)
if refined:
    return refined
return fallback_rule

def active_blob_thresholds(img): img_w, img_h = image_size(img) if img_w <= 160 or img_h <= 120: return MIN_BLOB_PIXELS_QQVGA, MIN_BLOB_AREA_QQVGA return MIN_BLOB_PIXELS, MIN_BLOB_AREA

def insert_candidate(candidates, candidate): score = candidate["score"] inserted = False for idx in range(len(candidates)): if score > candidates[idx]["score"]: candidates.insert(idx, candidate) inserted = True break

if not inserted:
    candidates.append(candidate)

if len(candidates) > MAX_SHAPE_CANDIDATES:
    candidates.pop()

def find_color_blobs(img, color_rule): pixels_threshold, area_threshold = active_blob_thresholds(img) try: return img.find_blobs( [color_rule["threshold"]], pixels_threshold=pixels_threshold, area_threshold=area_threshold, merge=True, margin=10, x_stride=BLOB_X_STRIDE, y_stride=BLOB_Y_STRIDE, ) except TypeError: # Older firmware may not support stride keywords. return img.find_blobs( [color_rule["threshold"]], pixels_threshold=pixels_threshold, area_threshold=area_threshold, merge=True, margin=10, )

def min_quad_features(blob): corners = min_corners_list(blob) if len(corners) != 4: return [], 0, 999.0

area = polygon_area(corners)
if area <= 0:
    return corners, 0, 999.0

fill = safe_feature(blob, "pixels", 0) / area
return corners, fill, polygon_side_ratio(corners)

def is_circle_like_blob(features): fill_circle_like = ( CIRCLE_BBOX_FILL_MIN <= features["fill_ratio"] <= CIRCLE_BBOX_FILL_MAX and features["bbox_aspect"] <= CIRCLE_BBOX_ASPECT_MAX ) perimeter_circle_like = ( fill_circle_like and features["circularity"] >= CIRCLE_CIRCULARITY_GUARD_MIN ) return fill_circle_like or perimeter_circle_like

def find_best_rect(img, blob, roi): try: rects = img.find_rects(roi=roi, threshold=RECT_THRESHOLD) except Exception: return 0, [], 0

best_score = 0
best_corners = []
best_fill = 0
center_limit = max(blob.w, blob.h) * RECT_CENTER_TOLERANCE_RATIO
center_limit2 = center_limit * center_limit

for rect in rects:
    rx, ry, rw, rh = rect_tuple(rect)
    rcx, rcy = normalize_point_to_image(rx + (rw / 2), ry + (rh / 2), roi, blob)
    if point_distance2(rcx, rcy, blob.cx, blob.cy) > center_limit2:
        continue

    corners = corners_list(rect)
    if len(corners) != 4:
        continue

    image_corners = []
    for corner in corners:
        image_corners.append(normalize_point_to_image(corner[0], corner[1], roi, blob))

    side_ratio = polygon_side_ratio(image_corners)
    if side_ratio > RECT_SIDE_RATIO_MAX:
        continue

    rect_area = polygon_area(image_corners)
    if rect_area <= 0:
        continue

    area_ratio = rect_area / max(1, blob.w * blob.h)
    if area_ratio < RECT_AREA_RATIO_MIN or area_ratio > RECT_AREA_RATIO_MAX:
        continue

    rect_fill = safe_feature(blob, "pixels", 0) / rect_area
    if rect_fill < RECT_FILL_MIN:
        continue

    score = safe_feature(rect, "magnitude", 1)
    if score > best_score:
        best_score = score
        best_corners = image_corners
        best_fill = rect_fill

return best_score, best_corners, best_fill

def find_best_circle(img, blob, roi): diameter = min(blob.w, blob.h) r_min = max(3, int(diameter CIRCLE_RADIUS_MIN_RATIO)) r_max = max(r_min + 2, int(diameter CIRCLE_RADIUS_MAX_RATIO))

try:
    circles = img.find_circles(
        roi=roi,
        threshold=CIRCLE_THRESHOLD,
        x_margin=CIRCLE_MARGIN,
        y_margin=CIRCLE_MARGIN,
        r_margin=CIRCLE_MARGIN,
        r_min=r_min,
        r_max=r_max,
        r_step=CIRCLE_R_STEP,
    )
except Exception:
    return 0, None, 0

best_score = 0
best_circle = None
best_fill = 0
center_limit = max(blob.w, blob.h) * CIRCLE_CENTER_TOLERANCE_RATIO
center_limit2 = center_limit * center_limit

for circle in circles:
    cx, cy, radius, magnitude = circle_tuple(circle)
    cx, cy = normalize_point_to_image(cx, cy, roi, blob)
    if radius <= 0:
        continue
    if point_distance2(cx, cy, blob.cx, blob.cy) > center_limit2:
        continue

    circle_area = math.pi * radius * radius
    if circle_area <= 0:
        continue

    circle_fill = safe_feature(blob, "pixels", 0) / circle_area
    if circle_fill < CIRCLE_FILL_MIN or circle_fill > CIRCLE_FILL_MAX:
        continue

    score = magnitude if magnitude else 1
    if score > best_score:
        best_score = score
        best_circle = (cx, cy, radius)
        best_fill = circle_fill

return best_score, best_circle, best_fill

def make_shape_features(img, blob, threshold): roi = expanded_roi(img, blob, ROI_MARGIN) rect_score, rect_corners, rect_fill = find_best_rect(img, blob, roi) circle_score, circle, circle_fill = find_best_circle(img, blob, roi) quad_corners, quad_fill, quad_side_ratio = min_quad_features(blob)

return {
    "roi": roi,
    "rect_score": int(rect_score),
    "rect_corners": rect_corners,
    "rect_fill": rect_fill,
    "quad_corners": quad_corners,
    "quad_fill": quad_fill,
    "quad_side_ratio": quad_side_ratio,
    "circle_score": int(circle_score),
    "circle": circle,
    "circle_fill": circle_fill,
    "density": safe_feature(blob, "density", 0),
    "fill_ratio": blob_fill_ratio(blob),
    "bbox_aspect": bbox_aspect_ratio(blob),
    "circularity": circularity_from_blob(blob),
}

def classify_shape_by_contour(img, blob, threshold): features = make_shape_features(img, blob, threshold) circle_like_blob = is_circle_like_blob(features) strong_square = ( len(features["quad_corners"]) == 4 and features["quad_fill"] >= STRONG_SQUARE_QUAD_FILL_MIN and features["quad_side_ratio"] <= MIN_QUAD_SIDE_RATIO_MAX ) min_quad_is_square = ( len(features["quad_corners"]) == 4 and features["quad_fill"] >= MIN_QUAD_FILL_MIN and features["quad_side_ratio"] <= MIN_QUAD_SIDE_RATIO_MAX and (not circle_like_blob or strong_square) )

# Native detector priority, with conflict handling. Circles can produce
# rectangle detections, so a low-fill rectangle loses to a valid circle.
if (features["circle_score"] > 0 or circle_like_blob) and not strong_square:
    if (
        (features["rect_score"] <= 0 and not min_quad_is_square)
        or (features["rect_fill"] < SQUARE_LIKE_FILL_MIN and features["quad_fill"] < MIN_QUAD_FILL_MIN)
    ):
        return "CIRCLE", features

if features["circle_score"] > 0 and not strong_square and (
    (features["rect_score"] <= 0 and not min_quad_is_square)
    or (features["rect_fill"] < SQUARE_LIKE_FILL_MIN and features["quad_fill"] < MIN_QUAD_FILL_MIN)
):
    return "CIRCLE", features

if (features["rect_score"] > 0 and not circle_like_blob) or min_quad_is_square:
    return "SQUARE", features

if (features["circle_score"] > 0 or circle_like_blob) and not strong_square:
    return "CIRCLE", features

# Triangle is deliberately a final, conservative fallback to avoid sending
# weak circle/square detections to TRI just because the detector is strict.
if (
    features["density"] <= TRIANGLE_DENSITY_MAX
    and features["fill_ratio"] <= TRIANGLE_FILL_MAX
    and features["quad_fill"] < MIN_QUAD_FILL_MIN
    and features["circularity"] < CIRCLE_LIKE_FILL_MIN
):
    return "TRIANGLE", features

return None, features

def detect_shape_command(img): candidates = [] best = None best_score = 0

for color_rule in COLOR_RULES:
    blobs = find_color_blobs(img, color_rule)
    for blob in blobs:
        insert_candidate(
            candidates,
            {
                "blob": blob,
                "color_rule": color_rule,
                "score": blob_score(blob),
            },
        )

for candidate in candidates:
    blob = candidate["blob"]
    color_rule = candidate["color_rule"]
    shape_name, features = classify_shape_by_contour(img, blob, color_rule["threshold"])
    if not shape_name:
        continue

    color_rule = refine_color_rule(img, blob, color_rule)
    score = candidate["score"]
    if score <= best_score:
        continue

    best = {
        "blob": blob,
        "color_name": color_rule["name"],
        "draw_color": color_rule["draw_color"],
        "shape_name": shape_name,
        "features": features,
        "source": "%s_%s" % (color_rule["name"], shape_name),
        "wave": SHAPE_RULES[shape_name]["wave"],
        "freq_hz": color_rule["freq_hz"],
        "amp_mvpp": color_rule["amp_mvpp"],
    }
    best_score = score

if best:
    blob = best["blob"]
    img.draw_rectangle(blob.rect, color=best["draw_color"])
    img.draw_cross((blob.cx, blob.cy), color=(255, 255, 255))
    circle = best["features"]["circle"]
    corners = best["features"]["rect_corners"]
    if not corners:
        corners = best["features"]["quad_corners"]
    if best["shape_name"] == "CIRCLE" and circle:
        img.draw_circle((int(circle[0]), int(circle[1]), int(circle[2])), color=best["draw_color"])
    elif best["shape_name"] == "SQUARE" and len(corners) == 4:
        for idx in range(4):
            img.draw_line(
                (
                    int(corners[idx][0]),
                    int(corners[idx][1]),
                    int(corners[(idx + 1) % 4][0]),
                    int(corners[(idx + 1) % 4][1]),
                ),
                color=best["draw_color"],
            )

return best

csi0 = csi.CSI() csi0.reset() csi0.pixformat(csi.RGB565) csi0.framesize(csi.QQVGA) csi0.snapshot(time=2000) csi0.auto_gain(False) # must be turned off for stable color tracking csi0.auto_whitebal(False) # must be turned off for stable color tracking try: csi0.auto_exposure(False) except Exception: pass

uart = UART(UART_ID, UART_BAUDRATE, timeout_char=200) clock = time.clock()

current_result = normalize_result(make_no_target_result()) last_send_ms = time.ticks_ms() seq = 0 tx_count = 0 frame_count = 0

print("OpenMV single-shape recognition started.") print("UART%d %d baud, frame=%s" % (UART_ID, UART_BAUDRATE, FRAME_VERSION))

while True: clock.tick() frame_count += 1 img = csi0.snapshot() target = detect_shape_command(img) if target: current_result = normalize_result(make_target_result(target)) else: current_result = normalize_result(make_no_target_result())

now = time.ticks_ms()
if time.ticks_diff(now, last_send_ms) >= SEND_PERIOD_MS:
    frame = build_frame(seq, current_result)
    uart.write(frame)
    if DEBUG_USB_PRINT:
        print(frame, end="")
    seq = (seq + 1) % 100000
    tx_count += 1
    last_send_ms = now

draw_status(img, current_result, clock.fps(), tx_count, target)

if frame_count >= GC_PERIOD_FRAMES:
    gc.collect()
    frame_count = 0
J
j7r6j9lehpio

这是现在的代码

2026-07-25 17:59
J
j7r6j9lehpio

现在又会卡死了,虽然还是很低的分辨率

image.png
2026-07-25 20:12
J
j7r6j9lehpio

你们周末是不上班吗?那周一还会看这条帖子吗?

2026-07-30 09:04
8
zlc9527

有解决吗

2026-07-30 09:49
Z
星小瞳xs

运行hello world.py,如果运行正常则证明是你所写的代码过于复杂,需要进行优化

2026-07-30 10:46
8
zlc9527

运行示例程序也会卡死,是示例太复杂了吗,单跑# 检测 AprilTag,按面积降序排序 tags = sorted( img.find_apriltags(fx=f_x, fy=f_y, cx=c_x, cy=c_y), key=lambda x: x.w * x.h, reverse=True, ) 跑一会就卡死了

2026-07-30 10:52
8
zlc9527

基于 OpenMV 的 AprilTag 检测脚本(无 MAVLink 发送)

功能:检测画面中的 AprilTag,计算距离并显示,LED 指示状态

import math import csi import time

---------- 相机与镜头参数 ----------

lens_mm = 2.8 # 镜头焦距 (mm) lens_to_camera_mm = 22 # 镜头到相机距离 (mm),当前未使用 sensor_w_mm = 4.592 # For OV5650 sensor sensor_h_mm = 3.423 # For OV5650 sensor

x_res = 160 # QQVGA 分辨率宽度 y_res = 120 # QQVGA 分辨率高度

计算像素焦距和主点

f_x = (lens_mm / sensor_w_mm) x_res f_y = (lens_mm / sensor_h_mm) y_res c_x = x_res / 2 c_y = y_res / 2

水平与垂直视场角

h_fov = 2 math.atan((sensor_w_mm / 2) / lens_mm) v_fov = 2 math.atan((sensor_h_mm / 2) / lens_mm)

---------- 相机初始化 ----------

csi0 = csi.CSI() csi0.reset() csi0.pixformat(csi.GRAYSCALE) csi0.framesize(csi.QQVGA) csi0.snapshot(time=2000)

clock = time.clock() while True: clock.tick() img = csi0.snapshot()

# 检测 AprilTag,按面积降序排序
tags = sorted(
    img.find_apriltags(fx=f_x, fy=f_y, cx=c_x, cy=c_y),
    key=lambda x: x.w * x.h,
    reverse=True,
)
print("FPS %f" % clock.fps())

只跑检测AprilTag就卡死了,运行不了十

几秒钟

2026-07-30 15:26
Z
星小瞳xs

跑这个

image.png