logo

如何遍历 find_blobs() 返回的多个 blob 并获取每个 blob 的 x 坐标?

2026-06-16 21:20
6
68uq5fmvji90

如何遍历 find_blobs() 返回的多个 blob 并获取每个 blob 的 x 坐标?

问题描述

当调用 image.find_blobs() 函数识别多个颜色区域时,返回的是一个 blob 列表(list)。若直接访问 blob.x(),实际是访问列表中第一个 blob 的 x 坐标;用户希望了解:如何正确遍历该列表,依次获取每个 blob 的 x 坐标。

关键要点

  • find_blobs() 返回的是 Python 列表,例如:blobs = img.find_blobs(...)
  • 需通过 for 循环或索引方式遍历 blobs 列表
  • 每个元素都是 Blob 对象,支持 .x(), .y(), .w(), .h(), .cx(), .cy() 等方法

示例代码

blobs = img.find_blobs(thresholds, pixels_threshold=100, area_threshold=100)

# 方法1:for 循环遍历
for b in blobs:
    print("Blob x:", b.x())

# 方法2:带索引遍历
for i, b in enumerate(blobs):
    print(f"Blob {i+1} x:", b.x())

# 方法3:提取所有 x 坐标到列表
x_coords = [b.x() for b in blobs]
print("所有 x 坐标:", x_coords)

补充说明

  • 确保 thresholds 是合法的颜色阈值列表(如 [[30, 100, -64, -8, -32, 32]])
  • 建议添加 if blobs: 判断,避免空列表导致逻辑异常
  • 如需同时获取坐标、大小、中心点等,可一并调用 b.cx(), b.cy(), b.w(), b.h() 等
2026-06-16 21:27
6
68uq5fmvji90

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())

6
68uq5fmvji90

这段代码是这样的:

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())

运行后系统报错:TypeError:'blob' object isn't iterable

这是什么原因,应该如何修改

2026-06-17 09:25
Z
星小瞳xs

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