hans

hans

【Opencv】cv2.rectangle出错


错误提示:

TypeError: Required argument 'rec' (pos 2) not found

源代码:

ori_img = img[0].detach().cpu().numpy()
ori_img = (ori_img*127.5 + 127.5).transpose([1,2,0]).astype(np.uint8)
x1, y1, x2, y2 = int(bb[0]), int(bb[1]), int(bb[2]), int(bb[3])
ori_img = cv2.rectangle(img=ori_img, pt1=(x1, y1), pt2=(x2, y2), color=(255, 255, 0), thickness=2)

出现上述错误,网上查,99% 都是让你把顶点坐标都强制转换成 int 类型。但是在我这里,我已经做过强制转换了,还是出问题。

同时 ori_img 也做了 uint8 类型转换,按理说也没事。但其实问题恰恰就出现在了 ori_img 上。

下面是代码是修改后的,添加了一句话,调用了 np.ascontiguousarray 这么个函数,网上搜了一下解释是:
将一个内存不连续存储的数组转换为内存连续存储的数组,使得运行速度更快。

从字面意思不难理解,但是我不太理解为什么从 Tensor 一路转换下来的 numpy 矩阵会变得在内存上变得不连续。

ori_img = img[0].detach().cpu().numpy()
ori_img = (ori_img*127.5 + 127.5).transpose([1,2,0]).astype(np.uint8)
ori_img = np.ascontiguousarray(ori_img)
x1, y1, x2, y2 = int(bb[0]), int(bb[1]), int(bb[2]), int(bb[3])
ori_img = cv2.rectangle(img=ori_img, pt1=(x1, y1), pt2=(x2, y2), color=(255, 255, 0), thickness=2)
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.