我正在尝试从ip camera捕获视频并保存为avi视频文件。同时脚本将包含面的帧保存为jpeg文件。虽然脚本正在执行这些作业,但CPU使用率约为100%。因此,我想仅限于面部检测的帧速率。
我的代码是:
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
now = datetime.datetime.now()
strtime = str(now)
cap = cv2.VideoCapture('rtsp://root:root@10.10.10.56:554/stream/profile1=r')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('1/video/%s.avi' % strtime,fourcc, 10.0 , (960,540))
if cap.isOpened():
while(True):
if cap.set(cv2.CAP_PROP_FPS,4):
try:
ret, frame = cap.read()
if ret==True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
out.write(frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
faces = face_cascade.detectMultiScale(gray,
scaleFactor=1.5,
minNeighbors=6,
minSize=(30,30))
for (x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),
cv2.imwrite('1/frames/%sf%s.jpg'%(now,str(cap.get(cv2.CAP_PROP_POS_FRAMES))), frame)
cv2.imshow('frame', frame)
except KeyboardInterrupt:
cap.release()
out.release()
cv2.destroyAllWindows()
sys.exit(0)
pass
else:
print "Unable to connect"
cap.release()
out.release()
cv2.destroyAllWindows()
sys.exit(0)
我在许多不同的地方尝试了cv2.VideoCapture.set(cv2.CAP_PROP_FPS,2),但它没有用。有没有办法限制视频捕获fps?
答案 0 :(得分:4)
经过多次尝试,我找到了一个适合我需求的解决方案。我对帧进行了计数,并且每隔10帧就进行一次for循环以进行面部检测。当我将相机设置为流10 fps视频时,这应该意味着面部检测流是1 fps。
编码解决方案:
if int(cap.get(cv2.CAP_PROP_POS_FRAMES)) % 10 == 0:
faces = face_cascade.detectMultiScale(gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30))
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0))
cv2.imwrite('1/frames/%sf%s.jpg'%(now, str(cap.get(cv2.CAP_PROP_POS_FRAMES))), frame)