视频即将结束时,在函数'cv :: resize'中出现错误!ssize.empty()

时间:2019-04-12 17:15:00

标签: python opencv

我正在尝试使用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)

1 个答案:

答案 0 :(得分:0)

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

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