绘制矩形_opencv绘制矩形框时报错
opencv绘制矩形框时cv2.rectangle(img, (x1,y1), (x2,y2), color, thickness=1, lineType=cv2.LINE_AA)有时候会报两种错误TypeError: argument for rectangle() given by name ('thickness') and position (4)TypeError: Expected..
·
opencv绘制矩形框时
cv2.rectangle(img, (x1,y1), (x2,y2), color, thickness=1, lineType=cv2.LINE_AA)
有时候会报两种错误
- TypeError: argument for rectangle() given by name ('thickness') and position (4)
- TypeError: Expected Ptr<cv::UMat> for argument 'img'

对于第一种错误,可能是左上角坐标以及右下角的坐标为浮点数导致的类型报错使用int()整数化。
对于第二种错误,可能是img类型有错,改成以下两种格式都可以
img = img.astype(np.uint8)
img = img.astype(np.float32)
而我在写代码时踩了个坑,发现两种方法都不行,后来发现我使用了数组浅拷贝,导致类型转换出错。
我将torch tensor imgs图片数组转化成np arrays后,类型不对,直接取单个图像进行类型转换操作,然后绘制矩形框报了第一种错误(参数不对也可能报第二种)
imgs = imgs.numpy()
img = img[0]
img = img.astype(np.float32)
cv2.rectangle(img, (x1,y1), (x2,y2), color, thickness=1, lineType=cv2.LINE_AA)
原因是numpy直接赋值是浅拷贝,使用深拷贝就可以解决类型转换报的错。可以两种方式
img = imgs[0].copy() # 深拷贝
img = img.astype(np.float32)
或直接对imgs类型转换
imgs = imgs.astype(np.float32)
img = imgs[0]
然后再对img绘制矩形框就不报错了。
更多推荐
所有评论(0)