TypeError:切片索引必须是整数或没有整数或具有__index__方法.如何解决它


 if w<h:
        normalized_char = np.ones((h, h), dtype='uint8')
        start = (h-w)/2
        normalized_char[:, start:start+w] = char
    else:
        normalized_char = np.ones((w, w), dtype='uint8')
        start = (w-h)/2
        normalized_char[start:start+h, :] = char

在jupyter上运行此错误

<ipython-input-8-15d17de04b9c> in extractCharactersNew(function)
     60             normalized_char = np.ones((h, h), dtype='uint8')
     61             start = (h-w)/2
---> 62             normalized_char[:, start:start+w] = char
     63         else:
     64             normalized_char = np.ones((w, w), dtype='uint8')
TypeError: slice indices must be integers or None or have an __index__ method

如何解决此错误?

您的错误是: -

TypeError: slice indices must be integers or None or have an __index__ method

slice indices,在您的情况下,请参阅您用来切片列表的变量

normalized_char[:, start:start+w] = char

是-startstart+w。对于列表切片,它们必须是整数或具有__index__方法。此__index__方法是一种特殊方法,它返回该对象的整数值。您应该能够通过确保提供正确的slice indices来解决问题。您可以使用start = (h-w)//2(整数部门)来确保启动是整数。

最新更新