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

在使用Python3进行矩阵操作时,当内部含有除法时结果的是浮点型,与原数据类型不一致,会产生错误:TypeError: slice indices must be integers or None or have an __index__ method

crow,ccol = rows/2 , cols/2
mask = np.zeros((rows,cols,2),np.uint8)

解决办法:将 / 改为 //

crow,ccol = rows//2 , cols//2
mask = np.zeros((rows,cols,2),np.uint8)

原因:在Python2中,除法的取值结果取整数:5/2 结果是整型 2

而在Python3中,除法/的结果包含小数:5/2 结果是浮点型 2.5;如果只想取整数需要使用 // ,即5//2 结果为整型 2

由于除法/自动产生的类型是浮点型,因此出现上述错误,将 / 更改为 // 即可

猜你喜欢

转载自blog.csdn.net/zhangpan929/article/details/86062978