【发布时间】:2021-07-03 16:32:22
【问题描述】:
所以我创建了一个神经网络 (CNN),可以使用 opencv 实时预测一个人的性别,一切正常,但是,当我运行代码时,OpenCv 有很多延迟,我的网络摄像头还不错,这是我的代码
'''
Real-time Face Gender Recognition using Conv-Nueral Network (CNN) and Cv2
Here we predict the save model that it is train
'''
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
import numpy as np
import cv2
import os
import cvlib as cv
import imutils
# load the model
model = load_model('gender_detection.model')
# open webcams and initiate the camara
webcam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
classes = ['hombre', 'mujer']
# loop through frames
while webcam.isOpened():
# read frame from webcam
status, frame = webcam.read()
#webcam.set(cv2.CAP_PROP_FPS, 1000)
frame = cv2.flip(frame, 1)
# apply face detection
face, confidence = cv.detect_face(frame) # this detects that there is a face in the camara, cvlib does, but not if it is a man that detects the neural network
# loop through detected faces
for idx, f in enumerate(face):
# get corner points of face rectangle
# this only will draw a rectangle when the cvlib detects the face with the vars giving up there
startX, startY = f[0], f[1]
endX, endY = f[2], f[3]
# draw the rectangle over the face
cv2.rectangle(frame, (startX, startY), (endX, endY), (0,255,0), 2)
# crop the detected face region
face_crop = np.copy(frame[startY:endY, startX:endX])
if face_crop.shape[0] < 10 or face_crop.shape[1] < 10:
continue
# preprocessing for gender detection model
face_crop = cv2.resize(face_crop, (96,96))
face_crop = face_crop.astype("float") / 255.0
face_crop = img_to_array(face_crop)
face_crop = np.expand_dims(face_crop, axis=0)
# apply gender detection face with the model
conf = model.predict(face_crop)[0]
# get label with max acc
idx = np.argmax(conf)
label = classes[idx]
label = "{}: {:.2f}".format(label, conf[idx] * 100)
Y = startY - 10 if startY - 10 > 10 else startY + 10
# write label and confidence above the face rectangle
cv2.putText(frame, label, (startX, Y), cv2.FONT_HERSHEY_SIMPLEX,
0.7, (0,255,0), 2)
# display output
cv2.imshow("Gender Detection", frame)
# press "Q" to stop
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#realese resources
webcam.release()
cv2.destroyAllWindows()
我也尝试使用 cv2.CAP_PROB_FPS 但这只是一点点帮助,没有多大帮助。
【问题讨论】:
-
推理需要多长时间?
-
@Christoph Rackwitz 我该如何检查,或者那是什么?
-
在代码的不同位置获取
time.time(),这样您就可以看到每个步骤需要多长时间。我猜面部识别是你的时间发生的地方 -
@TimRoberts 我试了一下,所有部分都是一样的,但是当我的脸的绿色方块在opencv中没有出现(遮住我的脸)时,它变得更快,不是很快但更快
-
2 wffectstcan 发生:1. 你的处理速度很慢(如果你需要处理,你不能删除它)。 2.您的处理速度很慢,并且视频捕获提供了旧帧。您可以通过多线程捕获来改善这一点,并且只将最新的帧提供给处理。这里的问题是:例如,如果相机提供 25 fps 并且 videocapture 具有 4 帧的缓冲区并且处理具有 1 fps,那么您将获得 4 秒而不是 1 秒的延迟。
标签: python opencv machine-learning