opencv错误解决:TypeError: an integer is required (got type tuple)
错误原因
-
最近在复现 YOLO 代码,其中要通过自己写的
Dataset
对数据进行增强,相关代码如下:def random_flip(self): # keep image and it's box unchanged if random.random() < 0.1: pass else: # flip the image in horizontal axis h, w, _ = self.img.shape self.img = np.fliplr(self.img) x_min, x_max = self.box[0], self.box[2] # bounding box also flip x_min, x_max = w - x_max, w - x_min self.box[0], self.box[2] = x_min, x_max
-
具体的内容是,将一个
image
在水平方向翻转,同时其对应的bounding box
也要进行翻转,然后要为了保证操作是正确的,又写了一个可视化函数:def draw(self): plt.imshow(self.raw_img) plt.show() x_min, y_min = self.box[:2] x_max, y_max = self.box[2:] temp = cv2.rectangle(self.img , (int(x_min), int(y_min)) , (int(x_max), int(y_max)) , (0, 255, 0) , 2) plt.figure() plt.imshow(temp) plt.show()
-
但是报错:
TypeError: an integer is required (got type tuple)
- 报错的位置是
cv2.rectangle
,经过排查我最后得出结论,是因为img
进行flip
之后,在空间存储中不连续导致的
解决方案
-
所以在函数中,应该如下操作保证
flip
的array
在空间中的连续性:self.img = np.fliplr(self.img) self.img = np.ascontiguousarray(self.img)
-
当然如果不执行这一步,也没问题,只是如果你想将图片可视化一下,还是要注意这个问题