You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从CSV提取坐标绘制图像轮廓时遇'int'不可迭代错误求助

解决cv2.polylines中'int' object is not iterable错误的方案

你碰到的这个错误,核心原因很明确:你试图把单个整数传给tuple()函数,而tuple()需要接收可迭代对象(比如列表、数组),整数本身不能被迭代,所以抛出了这个异常。另外你的代码逻辑还有个小问题:cv2.polylines是用来批量绘制折线/轮廓的,没必要在循环里每次只传一个点去调用它,效率低还容易出问题。

下面给你一步步修正的方案:

1. 先收集所有坐标点

首先把CSV里的所有(x,y)坐标收集成一个元组列表,不要在循环里急着绘制:

# 先导入pandas(你原来的代码里用了pd但没导入,记得加上)
import pandas as pd

# 收集所有点
points = []
for i in range(len(point5)):
    x = int(point5.values[i][1])
    y = int(point5.values[i][2])
    # 直接把x,y封装成元组加入列表,不需要tuple()包裹单个值
    points.append( (x, y) )

# 或者用更简洁的pandas写法
points = point5.apply(lambda row: (int(row[1]), int(row[2])), axis=1).tolist()

2. 转换为cv2.polylines要求的格式

OpenCV的polylines函数对输入的点集有严格要求:必须是numpy数组,且形状为(N, 1, 2)(N是点的数量),数据类型为np.int32。我们可以这样转换:

points_np = np.array(points, np.int32).reshape((-1, 1, 2))

3. 一次性绘制轮廓

现在可以调用polylines绘制完整轮廓了,注意参数的正确性:

# 绘制闭合轮廓(isClosed=True),颜色红色,厚度4
img_with_contour = cv2.polylines(image5, [points_np], isClosed=True, color=(0, 0, 255), thickness=4)

# 显示结果
cv2.imshow("contour", img_with_contour)
cv2.waitKey(0)
cv2.destroyAllWindows()

完整修正后的代码

把这些整合到你的代码里,完整版本如下:

import numpy as np
import cv2
import pandas as pd  # 补充导入pandas
import matplotlib.pyplot as plt

image5 = cv2.imread("C:/Users/Pc/Desktop/code prjt/5_Vesicule.jpg")
cv2.imshow("im", image5)
cv2.waitKey()

centrev5 = pd.read_csv("C:/Users/Pc/Desktop/code prjt/centrev5.csv", sep=";")
print(centrev5)
cx = int(centrev5.get(['centreX'])[0])
cy = int(centrev5.get(['centreY'])[0])
image = cv2.circle(image5, (cx, cy), radius=0, color=(255, 0, 0), thickness=10)
cv2.imshow("centre", image)
cv2.waitKey()

point5 = pd.read_csv("C:/Users/Pc/Desktop/code prjt/point5.csv", sep=";")
print(point5)

# 收集所有点
points = []
for i in range(len(point5)):
    x = int(point5.values[i][1])
    y = int(point5.values[i][2])
    points.append( (x, y) )

# 转换为OpenCV要求的格式
points_np = np.array(points, np.int32).reshape((-1, 1, 2))

# 绘制轮廓
img_with_contour = cv2.polylines(image5, [points_np], isClosed=True, color=(0, 0, 255), thickness=4)
cv2.imshow("contour", img_with_contour)
cv2.waitKey(0)
cv2.destroyAllWindows()

为什么原来的代码会报错?

  • tuple(x):这里的x是单个整数,而tuple()函数需要接收一个可迭代对象(比如[x,y])才能生成元组。你想要的是(x,y)这样的坐标元组,直接写就可以,完全不需要用tuple()包裹单个整数。
  • 循环内反复调用polylines:这个函数设计用来处理多点集合,每次只传一个点不仅浪费性能,还不符合函数的使用场景,容易引发参数格式错误。

内容的提问来源于stack exchange,提问作者kaouter berrahal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:17:40