代码段:
boxes =y.detach().numpy()
for box in boxes:
# cx, cy, w, h,
x1 = int(box[1] - box[3] // 2)
y1 = int(box[2] - box[4] // 2)
x2 = int(box[1] + box[3] // 2)
y2 = int(box[2] + box[4] // 2)
draw = cv2.rectangle(img_init,(x1,y1),(x2,y2),color=(0,255,0))#thickness=2
今天编写cv2相关代码遇见一个很奇怪的错误:TypeError: rectangle() missing required argument 'rec' (pos 2) ,但我仔细对照下图中的参数并没有出现上面的问题。
def rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None): # real signature unknown; restored from __doc__
后来我将计算后的值打印出来发现出现了下图中的 越界错误,像素点的坐标应该在Pytorch中有限制,而且现实中应该也不大可能出现万亿级别的像素坐标。
修改后的代码:
boxes =y.detach().numpy()
for box in boxes:
# cx, cy, w, h,
x1 = int(box[1] - box[3] // 2)
y1 = int(box[2] - box[4] // 2)
x2 = int(box[1] + box[3] // 2)
y2 = int(box[2] + box[4] // 2)
# 加入异常判断,剔除异常数据
if x1 >= 10000 or y1 >= 10000 or x2 >= 10000 or y2 >= 10000 or \
x1 < 0 or y1 < 0 or x2 < 0 or y2 < 0 :
continue
print([x1,y1,x2,y2, cfg.CLASSES_LIST[int(box[-1])]])
draw = cv2.rectangle(img_init,(x1,y1),(x2,y2),color=(0,255,0))#thickness=2
加入判断,将异常数据剔除即可。
最坑的是cv2并没有报越界错误,而是报的是缺少参数,或者参数位置不对。
中间查过一些报了同样错误的其他解决方法:1、cv2.imshow(winname, mat) 缺少参数winname;2、坐标没有转换为int类型。