ROS Python中OpenCV drawContours报错:无法解析轮廓,参数不支持序列协议
解决cv2.drawContours()的"Cant parse contours"报错问题
错误原因
cv2.drawContours()的第二个参数要求传入轮廓的序列(列表形式),但你代码中self.c是单个轮廓(numpy数组),不符合参数格式要求。- 初始化时
self.c = 0,当没有检测到轮廓时,self.c仍然是0,传入drawContours会直接引发类型错误。
修复步骤
- 修正self.c的初始化:在
__init__方法里把self.c = 0改成self.c = None,避免初始值为无效类型。 - 调整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
相关产品推荐
相关产品推荐

