解决python-opencv:(-215:Assertion failed) _img.empty() in function ‘cv::imwrite‘在将视频分成帧图片,写入时出现的问题

最近在搞视频检测问题,在用到将视频分帧保存为图片时,图片可以保存,但是会出现(-215:Assertion failed) !_img.empty() in function 'cv::imwrite'问题而不能正常运行,在检查代码、检查路径等措施均无果后,了解了视频分帧的原理后,才解决了问题,就这一个问题,解决了两天才解决,心态炸裂。缺少分帧结束的判断条件,在写入前,加上:

if frame is None;

           break

else:

#导入必备的文件库
import cv2
import numpy as np
import matplotlib.pyplot as plt

#读取视频并分帧为图片
def video_to_frame(video_path,save_path):
    video = cv2.VideoCapture(video_path)
    index = 0
    if video.isOpened():
          f =int(video.get(cv2.CAP_PROP_FPS))    #读取视频帧率
          print("The video's fps is ",f)  #显示视频帧率
          rval,frame = video.read()      #读取视频帧    
    else:
        rval = False
    while rval:
        print(index)
        rval,frame = video.read()
        
        cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)
        index += 1  
if __name__ == "__main__":
    video_to_frame(video_path="C:/Users/15603917325/Desktop/video_coal/coal/video/6.mp4",
                   save_path="C:/Users/15603917325/Desktop/video_coal/coal/pictures_coal")           
    print("succeed")

出现报错的原因很简单,在使用rval,frame读取视频的帧时,帧图片保存在frame对应的索引里。而在写入图片时,没有加入判断条件,当视频被分帧结束后,cv2.imread函数还在将空白信息写入文件夹,所以会出现报错,因此,只要在 cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)代码前一行加入判断条件,判断分帧结束后,停止写入即可。加入判断条件:

if frame is None:

            break

else:

就可以正确导入分帧后的图片了

在写入前加上判断条件:

#导入必备的文件库
import cv2
import numpy as np
import matplotlib.pyplot as plt

#读取视频并分帧为图片
def video_to_frame(video_path,save_path):
    video = cv2.VideoCapture(video_path)
    index = 0
    if video.isOpened():
          f =int(video.get(cv2.CAP_PROP_FPS))    #读取视频帧率
          print("The video's fps is ",f)  #显示视频帧率
          rval,frame = video.read()      #读取视频帧    
    else:
        rval = False
    while rval:
        print(index)
        rval,frame = video.read()
        if frame is None:
            break
        else:
            cv2.imwrite(save_path + "/"+ str(index)+".jpg",frame)
        index += 1  
if __name__ == "__main__":
    video_to_frame(video_path="C:/Users/15603917325/Desktop/video_coal/coal/video/6.mp4",
                   save_path="C:/Users/15603917325/Desktop/video_coal/coal/pictures_coal")           
    print("succeed")

正确输出分帧后的图片,并保存在文件夹中:

 


版权声明:本文为qq_54731673原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>