首页 > 解决方案 > 如何消除此错误:(-215:Assertion failed) !_img.empty() in function 'cv::imwrite'

问题描述

我正在尝试在 spyder python 3.7.1 中使用 opencv 4.1.2 从视频中提取帧。但是我收到了这个错误。

代码:

import cv2
print(cv2.__version__)
vidcap = cv2.VideoCapture('‪G:/TSR/TSR_vedios/blur/01_01_01_02_01.mp4')
success,image = vidcap.read()
count = 0
success = True
while success:
  cv2.imwrite("G:/TSR/TSR_vedios/tlevels/blurness/frame%d.jpg" % count, image)    
  success,image = vidcap.read()
  print ('Read a new frame: ', success)
  count += 1

标签: pythonopencv

解决方案


您需要调用该open函数并确保图像是有效的,即宽度和高度> 0。

像这样修改你的代码:

import cv2
print(cv2.__version__)
vidcap = cv2.VideoCapture()
success = vidcap.open('‪G:/TSR/TSR_vedios/blur/01_01_01_02_01.mp4')
if not success:
    print("Failed to open the video")

count = 0
while success:
    success,image = vidcap.read()
    height, width, channels = img.shape
    if (height > 0) and (width > 0):
        cv2.imwrite("G:/TSR/TSR_vedios/tlevels/blurness/frame%d.jpg" % count, image)    
        print('Read a new frame: ', success)
    else:
        print("Empty image")
    count += 1

推荐阅读