logo

遍历 find_blobs 返回的 blob 时出现 TypeError: 'blob' object isn't iterable

2026-06-16 21:31
6
68uq5fmvji90

遍历 find_blobs 返回的 blob 时出现 TypeError: 'blob' object isn't iterable

问题描述

用户在使用 OpenMV 的 img.find_blobs() 函数后,尝试遍历返回的每个 blob 对象的质心坐标(cx/cy),但代码报错:TypeError: 'blob' object isn't iterable。错误出现在嵌套 for 循环中:for b in blobs:,而 blobs 本身已是单个 blob 实例,不可迭代。

原始代码片段

for blobs in img.find_blobs([thresholds[2]], x_stride=4, y_stride=4, area_threshold=20, pixels_threshold=20):
    img.draw_rectangle(blobs.rect())
    img.draw_cross(blobs.cx(), blobs.cy())
    if blobs:
        for b in blobs:
            print("Blob cx:", b.cx(), "Blob cy:", b.cy())

关键错误点分析

  • find_blobs() 返回的是一个 blob 列表(list of blob objects),for blobs in ... 中的 blobs 是每次循环取出的单个 blob 对象,不是列表,因此不能再次 for b in blobs。
  • draw_cross 和 print 中应直接使用 blobs.cx(), blobs.cy(),无需二次遍历。
  • if blobs: 检查单个 blob 是否为真(总是 True,因 blob 对象非空),无实际必要;可删去或改为检查属性(如 blobs.pixels() > 0)。

建议修正写法

blobs = img.find_blobs([thresholds[2]], x_stride=4, y_stride=4, area_threshold=20, pixels_threshold=20)
for blob in blobs:  # ✅ 正确命名变量,避免歧义
    img.draw_rectangle(blob.rect())
    img.draw_cross(blob.cx(), blob.cy())
    print("Blob cx:", blob.cx(), "Blob cy:", blob.cy())
2026-06-17 09:25
Z
星小瞳xs

语法错误,建议参考IDE左上角:文件-示例中的代码