python - 当视频即将结束时,函数 '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)
解决方案
如果条件解决了我的问题,我的假设是正确的
if ret:
small_frame = cv2.resize(frame, None, fx=0.25, fy=0.25)
# reduce the res in quarter for faster processing
else:
break
推荐阅读
- reactjs - customStyleFn 是否覆盖内联样式?
- python - 根据下拉菜单的选择更新的 Tkinter 窗口
- r - 如何填充由直线和曲线创建的几何图形?
- javascript - 如何在 MongoDB 中展平 $lookup 生成的内部数组
- python - 在 Sympy 中,如何设置假设以便简化()函数在这个分段函数上工作?
- elasticsearch - 如何在 Grok Logstash 中获取 Json
- javascript - `arguments` 无法获取 `Destructuring` 参数的默认值?
- jquery - 如何在jquery中将多个项目保存到localStorage
- java - 用户只能输入 O 或 E 以外的任何内容将循环正确输入 JAVA
- c++ - 如何在 C++ 的函数中返回一个空的 Mat?