TypeError:切片索引必须是整数或None,或者在python 2.7中具有__index__方法


for file in zip(frames_list[-round(0.2 * len(frames_list)):], masks_list[-round(0.2 * len(masks_list)):]):
# Convert tensors to numpy arrays
frame = frame_batches.next().numpy().astype(np.uint8)
mask = mask_batches.next().numpy().astype(np.uint8)
# Convert numpy arrays to images
frame = Image.fromarray(frame)
mask = Image.fromarray(mask)
# Save frames and masks to correct directories
frame.save(DATA_PATH + '{}_frames/{}'.format(dir_name, dir_name) + '/' + file[0])
mask.save(DATA_PATH + '{}_masks/{}'.format(dir_name, dir_name) + '/' + file[1])
print("Saved {} frames to directory {}".format(len(frames_list), DATA_PATH))
print("Saved {} masks to directory {}".format(len(masks_list), DATA_PATH))

追溯

Traceback (most recent call last):
File "/home/khawar/Desktop/Khawar_Seg/main.py", line 190, in <module>
generate_image_folder_structure(frame_tensors, masks_tensors, frames_list, masks_list)
File "/home/khawar/Desktop/Khawar_Seg/main.py", line 173, in generate_image_folder_structure
for file in zip(frames_list[-round(0.2 * len(frames_list)):], masks_list[-round(0.2 * len(masks_list)):]):
TypeError: slice indices must be integers or None or have an __index__ method

python 2.7中的round函数返回float类型,但序列切片需要int作为参数。

>>> type(round(2.0))
<type 'float'>
>>> items = [0, 1, 2, 3, 4]
>>> items[round(2.0):]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: slice indices must be integers or None or have an __index__ method
# If we cast the rounded index to an int, it will work
>>> index = int(round(2.0))
>>> type(index)
<type 'int'>
>>> items[int(round(2.0)):]
[2, 3, 4]

因此,对于您的示例代码,在将索引用于切片(for循环的[<start>:<end>]部分(之前,需要将其强制转换为整数。

frames_index = -int(round(0.2 * len(frames_list)))
masks_index = -int(round(0.2 * len(masks_list)))
for file in zip(frames_list[frames_index:], masks_list[masks_index:]):
...

为了更容易阅读,我建议你使用一个函数来制作你的索引号:

def get_list_index(list_size):  # list_size is the len(<list>)
float_value = round(0.2 * list_size)
return -int(float_value)
frames_index = get_list_index(len(frames_list))
masks_index = get_list_index(len(masks_list))
for file in zip(frames_list[frames_index:], masks_list[masks_index:]):
...

编辑:

回答您评论中的问题:

对于zip(frames_list[-round(0.2 * len(frames_list)):]中的文件,:的含义是什么?

:以python切片表示法将开始索引与结束指数分离。

例如,如果您有列表['a', 'b', 'c', 'd', 'e'],并且只想获得从'b''d'的部分,那么您将使用一个从1开始到4-_1结束的切片,而不是'd'的索引。

>>> ['a', 'b', 'c', 'd', 'e'][1:4]
['b', 'c', 'd']

Python允许您使用索引,因此您可以从右侧倒数。我们可以使用-1而不是3:写入相同的切片

>>> ['a', 'b', 'c', 'd', 'e'][1:-1]
['b', 'c', 'd']

如果我们想让列表中的所有项从'b'开始一直到最后,我们可以将右侧索引更改为None,也可以将其省略:

>>> ['a', 'b', 'c', 'd', 'e'][1:None]
['b', 'c', 'd', 'e']
>>> ['a', 'b', 'c', 'd', 'e'][1:]
['b', 'c', 'd', 'e']

相关内容

最新更新