Dynamic face detection based on python OpenCV

  • 2020-09-28 08:59:12
  • OfStack

This article shares the specific code of python dynamic face detection for your reference. The specific content is as follows

Code directly: Press Q to exit


import cv2 
import numpy as np 
 
cv2.namedWindow("test") 
cap = cv2.VideoCapture(0) # Loading camera recording  
# cap = cv2.VideoCapture("test.mp4") # Open the video file  
success, frame = cap.read() 
# classifier = cv2.CascadeClassifier("/Users/yuki/anaconda/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml") 

#  Ensure that the xml The file with the py The file in 1 If not, change this to absolute path  
 
#haarcascade_frontalface_default.xml 
classifier = cv2.CascadeClassifier("/Users/yuki/anaconda/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml") 

#  Ensure that the xml The file with the py The file in 1 If not, change this to absolute path  
 
while success: 
 success, frame = cap.read() 
 size = frame.shape[:2] 
 image = np.zeros(size, dtype=np.float16) 
 image = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
 cv2.equalizeHist(image, image) 
 divisor = 8 
 h, w = size 
 minSize = (w // divisor, h // divisor) 
 faceRects = classifier.detectMultiScale(image, 1.2, 2, cv2.CASCADE_SCALE_IMAGE, minSize) 
 if len(faceRects) > 0: 
  for faceRect in faceRects: 
   x, y, w, h = faceRect 
   cv2.rectangle(frame,(x,y),(x+h,y+w),(0,255,0),2) 
   # lock   Eyes and mouth  
#cv2.circle(frame, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8), (255, 0, 0)) #  The left eye  
#cv2.circle(frame, (x + 3 * w //4, y + h // 4 + 30), min(w // 8, h // 8), (255, 0, 0)) # In the right eye  
#cv2.rectangle(frame, (x + 3 * w // 8, y + 3 * h // 4), (x + 5 * w // 8, y + 7 * h // 8), (255, 0, 0))# The mouth  
 cv2.imshow("test", frame) 
 key = cv2.waitKey(10) 
 c = chr(key & 255) 
 if c in ['q', 'Q', chr(27)]: 
  break 
cv2.destroyWindow("test") 

Related articles: