Python:Python3錯誤提示TypeError: slice indices must be integers or None or have an __index__ method解決辦法

機器視覺001發表於2020-11-14

Python:Python3錯誤提示TypeError: slice indices must be integers or None or have an __index__ method解決辦法

在執行Python 3指令碼時,報錯:TypeError: slice indices must be integers or None or have an __index__ method,報錯位置:

    # Now add left and right halves of images in each level
    ls_image = []
    for la, lb in zip(lp_image1, lp_image2):
        rows, cols, dpt = la.shape
        ls = np.hstack((la[:, 0:cols / 2], lb[:, cols / 2:]))
        ls_image.append(ls)

出錯程式碼行為:

ls = np.hstack((la[:, 0:cols / 2], lb[:, cols / 2:]))

問題原因:

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

解決方案:

將出錯程式碼行改為:

ls = np.hstack((la[:, 0:cols // 2], lb[:, cols // 2:]))

 

相關文章