ошибка Python: индексы кортежей должны быть целыми числами или срезами, а не кортежами - PullRequest
1 голос
/ 14 июня 2019

Я пытаюсь отобразить прямоугольники на изображении, используя cv2. Однако из-за следующей ошибки я не могу сделать их на изображении.

Я преобразовал изображение в массив numpy и попытался записать вершины по-разному, но общий формат правильный. Я не знаю, откуда появляется ошибка кортежа.

def draw_rect(img, dims, color = None):
    img = img.copy()
    dims = dims.reshape(-1, 4)
    if not color:
        color = (255, 255, 255)  #rgb values for white color

    for dim in dims:

        x, y = (dim[0], dim[1]) , (dim[2], dim[3])

        x = int(x[0]), int(x[1])
        y = int(y[0]), int(y[1])
        img = cv2.rectangle(img, x, y, color, int(max(img.shape[:,2])/200))  # error
    return img
def main():
    addr = 'test1_sec0.jpg'
    bbox = 'test1_sec0.jpg.csv'
    img_show(addr)  # used to read and show the image using cv2. Works fine.
    dims = bbox_read(bbox)  # used to read the boundary boxes. Works fine
    img = cv2.imread(addr, 1)
    img_data = np.asarray(img, dtype = 'int32') 
    print(img_data)
    plt.imshow(draw_rect(img_data, dims))  # error
    plt.show( )


if __name__ == '__main__':
    main()

 Traceback (most recent call last):
      File "ImgAug.py", line 56, in <module>
        main()
      File "ImgAug.py", line 51, in main
        plt.imshow(draw_rect(img_data, dims))
      File "ImgAug.py", line 41, in draw_rect
        img = cv2.rectangle(img, x[0], x[1], y[0], y[1], color, int(max(img.shape[:,2])/200))  # first argument & variable must be same cause same image should have all the bbox
    TypeError: tuple indices must be integers or slices, not tuple

1 Ответ

2 голосов
/ 14 июня 2019

img.shape является кортежем, но img.shape[:,2] пытается проиндексировать его с помощью другого кортежа, что недопустимо:

>>> class X:
...     def __getitem__(self, index):
...         print(f'The index is: {index}')
...         
>>> X()[:,2]
The index is: (slice(None, None, None), 2)

Как видите, something[:,2] фактически генерирует кортеж какиндекс.

...