首页 > 解决方案 > 当视频即将结束时,函数 'cv::resize' 中出现错误!ssize.empty()

问题描述

我正在尝试使用 cv2.resize 调整视频大小以加速人脸检测,如果我在完成之前停止进程,我的代码运行良好,它会在终止进程之前正常显示进度和输出但是如果我让它自己完成我得到上述错误并且没有输出。我的假设是在视频的末尾没有帧来调整它的大小,如何在此之前结束循环?

#this code uses openCV library to detect faces
#in a video provided in the same project folder
#a brief description is written under important lines of code describing its job

import cv2
import time
#importing necessarily libraries
start = time. time()


face_cascade = cv2.CascadeClassifier('C:\\Users\\moh00\\PycharmProjects\\try1\\venv\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_alt2.xml')
#choosing the right face classifier provided with openCV and importing it

cap = cv2.VideoCapture('thor.mp4')
#loading the video using cv2.VideoCapture (incase you want to use a webcam put 0 at file name or the webcam number ordering number)

fourCC = cv2.VideoWriter_fourcc(*'XVID')
#codec to used to write the video

out = cv2.VideoWriter('thorCV.avi',fourCC, 29.97, (1920,1080))
#output the video after detection, must use same FPS, (x,y)RES


while True:
    ret, frame = cap.read()

    small_frame = cv2.resize(frame, None, fx=0.25, fy=0.25)
# reduce the res in quarter for faster processing

    gray = cv2.cvtColor(small_frame, cv2.COLOR_BGR2GRAY)
    faces1 = face_cascade.detectMultiScale(gray,1.2,3)
    for (x,y,w,h) in faces1:
        cv2.rectangle(frame, (x*4,y*4), ((x+w)*4,(y+h)*4), (0,0,255), 2)
# scaling back to draw the rectangle at the right position


    out.write(frame)
    #output the video

    cv2.imshow('frame', frame)
    #show the video for face detection

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#a line used to end the loop (pressing q in the keyboard will terminate the process)


cap.release()
cv2.destroyAllWindows()
out.release()

end = time. time()
print(end - start)

标签: pythonopencv

解决方案


如果条件解决了我的问题,我的假设是正确的

    if ret:
        small_frame = cv2.resize(frame, None, fx=0.25, fy=0.25)
        # reduce the res in quarter for faster processing
    else:
        break

推荐阅读