项目目标:在管道中精确定位小钢球位置,通过OpenMV4 H7采集图像并实时输出至LCD。当前代码下LCD出现白屏或仅半屏显示(QQVGA分辨率下),而IDE图像显示完全正常;官方LCD示例可运行,说明LCD硬件及基础驱动无故障。同时,补光灯两侧小球识别效果明显下降。
import time\nimport sensor\nimport image\nfrom pyb import Pin, Timer, UART\nimport math\n\n# ====================== 硬件初始化 ======================\n\nlight = Timer(2, freq=10000).channel(1, Timer.PWM, pin=Pin("P6"))\nlight.pulse_width_percent(60)\nuart = UART(3, 115200)\n\n# ====================== 可调参数 ======================\n\n# LAB 阈值:根据你的小球颜色实测调整\n\nTHRESHOLDS = (22, 35, -56, -16, 45, 18)\n\n# 检测 ROI (x, y, w, h)\n\nBALL_ROI = (4, 60, 152, 20)\n\n# 色块筛选\n\nMIN_PIXELS = 5\nMIN_AREA = 5\n\n# 标定系数\n\nK_x = 1.689\n\n# 稳定点采集帧数(修改为50次)\n\nSTABLE_FRAMES = 50\n\n# 坐标量化精度(将坐标四舍五入到最近的grid_step倍数的网格)\n\nGRID_STEP = 2\n\n# ====================== 串口通信配置 ======================\n\n# 通信协议:\n\n# 1. d值(校准参数):采集完成后发送一次,格式:d{符号}{数值}\n\n# 2. x值(实时位置):每帧发送,格式:x{符号}{数值}\n\n# 例如:d+012\n 表示 d=+1.2\n# x-034\n 表示 x=-3.4\n\n# ====================== 摄像头初始化 ======================\n\nsensor.reset()\nsensor.set_hmirror(True)\nsensor.set_vflip(True)\nsensor.set_framesize(sensor.QQVGA)\nsensor.set_pixformat(sensor.RGB565)\nsensor.set_contrast(-2)\nsensor.set_auto_exposure(True)\ntime.sleep(0.5)\n\nclock = time.clock()\nframe_id = 0\nlast_ball = None\nmiss_count = 0\n\n# ====================== 稳定点识别相关变量 ======================\n\nstable_mode = True\nstable_positions = []\ntarget_x = None\ntarget_y = None\ntarget_set = False\nd_sent = False\n\nprint("系统启动...")\nprint("正在采集稳定点,请保持钢球静止...")\n\n# ====================== 辅助函数 ======================\n\ndef quantize_coord(coord):\n """将坐标量化到最近的网格点"""\n return int(round(coord / GRID_STEP) * GRID_STEP)\n\ndef find_mode_position(positions):\n """使用众数法找到最频繁出现的位置"""\n if not positions:\n return None, None\n\n freq_dict = {}\n for pos in positions:\n if pos in freq_dict:\n freq_dict[pos] += 1\n else:\n freq_dict[pos] = 1\n\n max_count = 0\n most_common_pos = None\n\n for pos, count in freq_dict.items():\n if count > max_count:\n max_count = count\n most_common_pos = pos\n\n if most_common_pos is not None:\n return most_common_pos[0], most_common_pos[1]\n else:\n return None, None\n\ndef get_position_frequency(positions, target_pos):\n """获取某个位置在列表中出现的次数"""\n count = 0\n for pos in positions:\n if pos == target_pos:\n count += 1\n return count\n\ndef format_value(value):\n """格式化数值为3位带符号字符串"""\n sign = '+' if value >= 0 else '-'\n abs_val = int(abs(value) * 10) # 乘以10保留1位小数\n abs_val = min(abs_val, 999) # 限制最大值\n return "%s%03d" % (sign, abs_val)\n\ndef send_d_value(d_value):\n """发送d值(只发送一次)"""\n d_str = format_value(d_value)\n uart.write("d%s\n" % d_str)\n\ndef send_x_value(x_value):\n """发送x值(每帧发送)"""\n x_str = format_value(x_value)\n uart.write("x%s\n" % x_str)\n\n# ====================== 主循环 ======================\n\nwhile True:\n clock.tick()\n img = sensor.snapshot()\n img.median(2)\n\n # ---- 色块检测(限定 ROI)----\n blobs = img.find_blobs(\n [THRESHOLDS],\n roi=BALL_ROI,\n pixels_threshold=MIN_PIXELS,\n area_threshold=MIN_AREA,\n merge=True\n )\n\n best_blob = None\n best_score = 0\n\n for b in blobs:\n w, h = b.w(), b.h()\n\n if b.roundness() < 0.6:\n continue\n if w < 4 or h < 4:\n continue\n\n score = b.pixels() * b.roundness()\n if score > best_score:\n best_score = score\n best_blob = b\n\n # ---- 更新钢球状态 ----\n if best_blob is not None:\n cx = best_blob.cx()\n cy = best_blob.cy()\n\n last_ball = best_blob\n miss_count = 0\n\n # ===== 稳定点采集模式 =====\n if stable_mode:\n # 将坐标量化后存储,减少噪声影响\n quantized_x = quantize_coord(cx)\n quantized_y = quantize_coord(cy)\n stable_positions.append((quantized_x, quantized_y))\n\n # 在图像上显示采集进度\n progress = len(stable_positions)\n img.draw_string(2, 20, "采集: %d/%d" % (progress, STABLE_FRAMES),\n color=(255, 255, 0))\n\n # 实时显示当前采集到的不同位置数量\n unique_positions = []\n for pos in stable_positions:\n if pos not in unique_positions:\n unique_positions.append(pos)\n img.draw_string(2, 30, "不同位置: %d" % len(unique_positions),\n color=(255, 255, 0))\n\n if len(stable_positions) >= STABLE_FRAMES:\n # 使用众数法找到最频繁出现的位置作为目标点\n target_x, target_y = find_mode_position(stable_positions)\n target_set = True\n stable_mode = False\n d_sent = False # 重置d值发送标记\n\n # 统计众数出现的次数\n mode_count = get_position_frequency(stable_positions, (target_x, target_y))\n\n # 采集完成后发送d值\n roi_center_x = BALL_ROI[0] + BALL_ROI[2] // 2\n d_value = (target_x - roi_center_x) * K_x\n send_d_value(d_value)\n d_sent = True\n\ print("稳定点采集完成!")\n print("目标点 (众数): (%d, %d)" % (target_x, target_y))\n print("出现次数: %d / %d (%.1f%%)" %\n (mode_count, STABLE_FRAMES, mode_count * 100.0 / STABLE_FRAMES))\n print("切换到正常运行模式...")\n print("串口格式: d值发送一次,x值每帧发送")\n\ # 采集模式下不发送数据(静默)\n\n else:\n # ===== 正常运行模式 =====\n if target_set:\n # 计算ROI中心X坐标\n roi_center_x = BALL_ROI[0] + BALL_ROI[2] // 2\n\n # 计算d值(稳定点相对ROI中心的偏移)\n d_value = (target_x - roi_center_x) * K_x\n\ # 计算x值(钢球相对稳定点的偏移)\n x_value = (cx - target_x) * K_x\n\ # 只发送x值\n send_x_value(x_value)\n\ # IDE显示\n img.draw_string(2, 2, "d=%.1f x=%.1f" % (d_value, x_value),\n color=(0, 255, 0))\n\ else:\n # 目标点未设定,发送默认x值\n send_x_value(0.0)\n\ else:\n miss_count += 1\n if miss_count >= 3:\n last_ball = None\n\ # 没有检测到小球,发送默认x值\n if not stable_mode and target_set:\n send_x_value(0.0)\n else:\n # 采集模式不发送数据\n pass\n\ # ---- 画面绘制 ----\n # ROI 框(调试用)\n img.draw_rectangle(BALL_ROI, color=(100, 100, 100))\n\n # ROI中心线(调试用)\n roi_center_x = BALL_ROI[0] + BALL_ROI[2] // 2\n img.draw_line(roi_center_x, 0, roi_center_x, 120, color=(150, 150, 150), thickness=1)\n\n # 绘制目标点(如果已设定)\n if target_set:\n # 目标点标记(紫色大圆点)\n img.draw_circle(target_x, target_y, 8, color=(255, 0, 255), thickness=2)\n img.draw_circle(target_x, target_y, 3, color=(255, 0, 255), fill=True)\n img.draw_string(target_x + 10, target_y - 5, "TARGET", color=(255, 0, 255))\n\ # 显示d值(稳定点偏移)\n roi_center_x = BALL_ROI[0] + BALL_ROI[2] // 2\n stable_offset = target_x - roi_center_x\n real_stable_offset = stable_offset * K_x\n img.draw_string(2, 12, "d=%.1f" % real_stable_offset, color=(0, 255, 255))\n\ # 绘制目标点到ROI中心的连线\n img.draw_line(target_x, target_y, roi_center_x, BALL_ROI[1] + BALL_ROI[3] // 2,\n color=(200, 100, 200))\n\ # 如果在采集模式,显示所有已采集的位置点(散点图)\n if stable_mode and len(stable_positions) > 0:\n # 显示采集点的分布(用小方块表示)\n start_idx = max(0, len(stable_positions) - 50)\n for idx in range(start_idx, len(stable_positions)):\n px, py = stable_positions[idx]\n # 使用小矩形代替像素点\n img.draw_rectangle(px-1, py-1, 3, 3, color=(255, 200, 0), fill=True)\n\ # 显示当前最频繁出现的位置(实时众数)\n if len(stable_positions) > 10:\n temp_x, temp_y = find_mode_position(stable_positions)\n if temp_x is not None and temp_y is not None:\n img.draw_circle(temp_x, temp_y, 5, color=(0, 255, 255), thickness=1)\n # 移除稳定点坐标显示\n # img.draw_string(temp_x + 8, temp_y - 3, "CURRENT MODE", color=(0, 255, 255))\n\ # 显示当前众数出现次数\n temp_count = get_position_frequency(stable_positions, (temp_x, temp_y))\n img.draw_string(2, 40, "众数次数: %d" % temp_count, color=(0, 255, 255))\n\ if last_ball is not None:\n x = last_ball.x()\n y = last_ball.y()\n w = last_ball.w()\n h = last_ball.h()\n cx = last_ball.cx()\n cy = last_ball.cy()\n\ # 画矩形框 + 十字\n img.draw_rectangle((x, y, w, h), color=(0, 255, 0), thickness=2)\n img.draw_cross(cx, cy, color=(255, 0, 0), size=8)\n\ # 如果目标点已设定,绘制小球到目标点的连线\n if target_set:\n img.draw_line(cx, cy, target_x, target_y, color=(255, 200, 0), thickness=2)\n # 显示x值(小球偏移)\n ball_offset = cx - target_x\n real_ball_offset = ball_offset * K_x\n img.draw_string(cx + 10, cy - 10, "x=%.1f" % real_ball_offset, color=(255, 200, 0))\n\ # 显示模式信息\n if stable_mode:\n img.draw_string(2, 2, "MODE:采集稳定点(众数法)", color=(255, 255, 0))\n # 移除当前众数坐标显示\n # if len(stable_positions) > 0:\n # temp_x, temp_y = find_mode_position(stable_positions)\n # if temp_x is not None and temp_y is not None:\n # img.draw_string(2, 50, "当前众数:(%d,%d)" % (temp_x, temp_y),\n # color=(0, 255, 255))\n else:\n img.draw_string(2, 2, "MODE:运行中", color=(0, 255, 0))\n if target_set:\n img.draw_string(2, 22, "目标:(%d,%d)" % (target_x, target_y),\n color=(255, 0, 255))\n\ # 帧率\n img.draw_string(2, 120 - 15, "FPS:%.1f" % clock.fps(), color=(255, 255, 255))\n\ frame_id += 1使用image库缩放和翻转图像,然后传输至LCD即可