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

视频分片存储数组:解决'NoneType不可下标'错误的修复方案

解决OpenCV视频帧分割时的TypeError: 'NoneType' object is not subscriptable错误

问题根源

使用cv2.VideoCapture读取视频时,cap.read()会返回ret(布尔值,标记帧读取是否成功)和frame(读取到的帧图像)。当视频读取到末尾或读取失败时,ret为False,此时frame是None。后续代码对None进行切片操作,就会触发TypeError: 'NoneType' object is not subscriptable错误。

修复后的完整代码

import cv2

cap = cv2.VideoCapture('Test_5_vid.MP4')
n_rows = 3
n_images_per_row = 3

while(True):
    # 逐帧读取视频
    ret, frame = cap.read()
    
    if not ret: # 新增关键判断:读取失败/视频结束时退出循环
        print('无法读取帧,结束循环')
        break
    
    height = 1080
    width = 1080

    roi_height = int(height / n_rows)
    roi_width = int(width / n_images_per_row)

    images = []

    for x in range(0, n_rows):
        for y in range(0,n_images_per_row):
            tmp_image=frame[x*roi_height:(x+1)*roi_height, y*roi_width:(y+1)*roi_width]
            images.append(tmp_image)
           
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


# 释放视频捕获资源
cap.release()
cv2.destroyAllWindows()

核心修复说明

  • 新增if not ret:分支:每次读取帧后立即检查ret状态,一旦读取失败或视频播放完毕,直接跳出循环,避免对None类型的frame进行后续操作,从根源上解决了该错误。

内容的提问来源于stack exchange,提问作者Sophia Tatarek

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:30:59