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

ROS Python中OpenCV drawContours报错:无法解析轮廓,参数不支持序列协议

解决cv2.drawContours()的"Cant parse contours"报错问题

错误原因

  • cv2.drawContours()的第二个参数要求传入轮廓的序列(列表形式),但你代码中self.c是单个轮廓(numpy数组),不符合参数格式要求。
  • 初始化时self.c = 0,当没有检测到轮廓时,self.c仍然是0,传入drawContours会直接引发类型错误。

修复步骤

  1. 修正self.c的初始化:在__init__方法里把self.c = 0改成self.c = None,避免初始值为无效类型。
  2. 调整drawContours的调用逻辑:
    • 每次处理图像前重置self.c为None;
    • 只有当self.c不为None时,才调用drawContours;
    • 把单个轮廓self.c包装成列表[self.c]传入第二个参数。

修改后的process_image方法代码

def process_image(self, cv_image):
    mask = cv2.inRange(cv_image, self.low_b, self.high_b)
    contours, hierarchy = cv2.findContours(mask, 1, cv2.CHAIN_APPROX_NONE)
    self.c = None  # 每次处理先重置为None
    if len(contours) > 0:
        self.c = max(contours, key=cv2.contourArea)
        M = cv2.moments(self.c)
        if M["m00"] != 0:
            cx = int(M["m10"] / M['m00'])
            cy = int(M["m01"] / M["m00"])
            print("CX: " + str(cx) + "  CY: " + str(cy))
            if cx >= 120:
                print("Turn Left")
            if cx < 120 and cx > 40:
                print ("On Track")
            if cx <= 40:
                print("Turn Right")
            cv2.circle(cv_image, (cx,cy), 5, (255,255,255), -1)
    else:
        print("I dont see the line")
    # 只有当self.c有效时才绘制轮廓
    if self.c is not None:
        cv2.drawContours(cv_image, [self.c], -1, (0, 255, 0), -1)
    image_message = self.bridge.cv2_to_imgmsg(cv_image, "passthrough")
    self.image_pub.publish(image_message)

额外提示

  • 你之前尝试替换成contours没解决,是因为当contours为空时,仍然会执行drawContours,所以必须加上非空判断。
  • 注意cv2.inRange的参数顺序:low_b是颜色下限,high_b是颜色上限,你当前代码里low_b = [5,5,5]、high_b = [0,0,0]会导致mask全黑,无法检测到任何内容,建议改成合理范围,比如检测黑色线的话应该是low_b = np.uint8([0,0,0]),high_b = np.uint8([5,5,5])。

内容的提问来源于stack exchange,提问作者Cooler Mann

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 16:27:49