使用OpenCV polyLines绘制YOLO分割掩码时报错(-215:Assertion failed)
YOLO分割掩码绘制错误修复
尝试绘制YOLO分割掩码时,使用cv2.polylines触发断言错误,相关信息如下:
标注行示例
36 0.6158357764423077 0.814453125 0.6158357764423077 0.8095703125 0.6070381225961539 0.8095703125 0.6041055721153846 0.8115234375 0.5894428149038462 0.8154296875 0.5747800576923077 0.8125 0.5513196490384615 0.8134765625 0.5483870961538462 0.81640625 0.5923753653846154 0.818359375 0.6158357764423077 0.814453125
原代码
image_height, image_width, c = img.shape isClosed = True color = (255, 0, 0) thickness = 2 with open(annotation_file) as f: for line in f: split_line = line.split() class_id = split_line[0] mask_shape = [float(numeric_string) for numeric_string in split_line[1:len(split_line)]] mask_points = [] for i in range(0,len(mask_shape),2): x,y = mask_shape[i:i+2] mask_points.append((x * image_width, y * image_height)) points = np.array([mask_points]) image = cv2.polylines(img, points, isClosed, color, thickness) break
错误信息(翻译后)
OpenCV(4.7.0) /Users/xperience/GHA-OCV-Python/_work/opencv-python/opencv-python/opencv/modules/imgproc/src/drawing.cpp:2434: 错误: (-215:断言失败) p.checkVector(2, CV_32S) >= 0 在函数 'polylines' 中
错误原因
cv2.polylines对输入点集有两个硬性要求:
- 坐标必须是32位整数(CV_32S),不能是浮点数
- 点集数组形状需符合
(点数, 1, 2)格式
原代码问题:
- 计算出的坐标为浮点数(如
x*image_width结果为小数) - 数组形状为
(1, N, 2),不符合要求格式
修正后的代码
import cv2 import numpy as np # 假设img已正确读取 image_height, image_width, c = img.shape isClosed = True color = (255, 0, 0) thickness = 2 with open(annotation_file) as f: for line in f: split_line = line.split() class_id = split_line[0] mask_shape = [float(numeric_string) for numeric_string in split_line[1:]] mask_points = [] for i in range(0, len(mask_shape), 2): x, y = mask_shape[i:i+2] # 转换为整数像素坐标 px = int(x * image_width) py = int(y * image_height) mask_points.append([px, py]) # 调整数组格式和类型,适配polylines要求 points = np.array(mask_points, np.int32).reshape((-1, 1, 2)) # 绘制多边形 image = cv2.polylines(img, [points], isClosed, color, thickness) break
关键修改点
- 坐标转整数:用
int()将浮点坐标转为像素级整数(也可根据需求用np.round()后转int) - 数组格式调整:通过
reshape((-1,1,2))将点集转为(N,1,2)形状,同时指定类型为np.int32 - 点集传递:用
[points]包裹,适配polylines接受多多边形点集列表的参数要求
内容的提问来源于stack exchange,提问作者219CID
相关产品推荐
相关产品推荐

