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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aiynmimi/article/details/87103999

问题

在执行一个脚本时,报错:TypeError: slice indices must be integers or None or have an __index__ method,报错位置:

start_width = (width_large - width_small) / 2
start_height = (height_large - height_small) / 2

img_large[start_height:start_height + height_small,
                  start_width:start_width + width_small] = img_small

这里最后一句切片的时候报错!

解决方案

出现这个问题的原因在于上边的start_widthstart_height都是浮点数,因为/运算得到的结果自动就是浮点数。比如:

>>> 10/5
>>> 2.0

而切片做索引是不支持浮点数的,所以这里要转换为int类型,或者将/换成//运算!

猜你喜欢

转载自blog.csdn.net/aiynmimi/article/details/87103999