You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python2转Python3遇IndexError:numpy数组索引类型错误排查

Python2迁移Python3时numpy索引报错的解决方法

问题核心

报错出现在interlace函数的inter[i, :, :] = img[val][i / NUM_FRAMES, :, :]行,触发IndexError的本质是Python2与Python3的除法行为差异:

  • Python2中,两个整数用/做除法会返回整数(地板除)
  • Python3中,/对整数除法返回浮点数,而numpy数组索引仅接受整数、切片、省略号等类型,浮点数无法作为合法索引。

解决方案

将除法运算符/替换为Python3的整数除法运算符//,强制返回整数结果:

修改后的interlace函数关键代码行:

inter[i, :, :] = img[val][i // NUM_FRAMES, :, :]

验证说明

替换后,i // NUM_FRAMES会输出整数类型,完全符合numpy数组的索引要求,不会再触发IndexError。你可以通过打印type(i // NUM_FRAMES)确认结果为<class 'int'>。

完整修改后的interlace函数

def interlace(img, h, w):
    inter = np.empty((h, w, 3), img[0].dtype)
    for i in range(h - 1):
        val = i % NUM_FRAMES
        print('index') 
        print(img[val])
        inter[i, :, :] = img[val][i // NUM_FRAMES, :, :]
    return inter

内容的提问来源于stack exchange,提问作者Rofie Sagara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 02:18:22