Python Realizes Face Detection and Saving Based on OpenCV

  • 2021-07-24 11:32:25
  • OfStack

In this paper, we share the example of Python based on OpenCV face detection, and save the specific code for your reference, the specific content is as follows

Installing opencv

If pip is installed, Opencv can be installed on windows directly through cmd command pip install opencv-python (only the main module is required), or you can enter the command pip install opencv-contrib-python (if main module and contrib module are required)
For details, please click here

Import opencv


import cv2

All packages contain haarcascade files. This document is very important! ! !
cv2.data. haarcascades can be used as a shortcut to the data folder. For example:


cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

Code


#-*- coding: utf-8 -*-
# import openCV Library of 
import cv2
import os, math, operator
from PIL import Image
from functools import reduce


### Call the computer camera to detect the face and take a screenshot 

def CatchPICFromVideo(window_name, path_name):
 cv2.namedWindow(window_name)

 # Computer camera 
 cap = cv2.VideoCapture(0)

 # Tell OpenCV Using a face recognition classifier 
 classfier = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")

 # The color of the border to be drawn after detecting the face 
 color = (0, 255, 0)

 while cap.isOpened():
 ok, frame = cap.read() # Read 1 Frame data 
 if not ok:
  break

 grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Converts the current frame image to a grayscale image 

 # Face detection, 1.2 And 2 They are the scaling ratio of the picture and the number of effective points to be detected 
 faceRects = classfier.detectMultiScale(grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32))
 if len(faceRects) > 0:  # Greater than 0 A face is detected 
  for faceRect in faceRects: # Box each separately 1 Zhang Face 
  x, y, w, h = faceRect

   # Draw a rectangular frame 
  cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)
  
  k = cv2.waitKey(100) # Every 0.1 Second read 1 Secondary keyboard 
  if k == ord("z") or k == ord("Z"): # If you enter z
   # Save the current frame as a picture 
   img_name = path_name
   print(img_name)
   image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
   cv2.imwrite(img_name, image,[int(cv2.IMWRITE_PNG_COMPRESSION), 9])
   break 
   
 # Display image 
 cv2.imshow(window_name, frame)
 # Exit the camera interface 
 c = cv2.waitKey(100)
 if c == ord("q") or c == ord("Q"): 
  break

 # Release the camera and destroy all windows 
 cap.release()
 cv2.destroyAllWindows()


os.system("cls") # Clear screen 
recogname = "recogface.jpg" # Pre-stored face file 
CatchPICFromVideo("get face",recogname)

Functions:

Although it can frame the face, the efficiency is not very high.
Press Z or z to intercept and save the framed face


Related articles: