This article shares the specific code that Python implements face detection based on OpenCV for your reference. The specific content is as follows
Install opencv
If pip is installed, Opencv can be installed directly through the cmd command for Windows installationpip install opencv-python(Only the main module is required), you can also enter commandspip install opencv-contrib-python(If you need the main module and the contrib module)
For details, please clickHere
Import opencv
import cv2
All packages contain haarcascade files. This file is very important!!!
Can be used as a shortcut to the data folder. For example:
( + "haarcascade_frontalface_default.xml")
Code
#-*- coding: utf-8 -*- # import openCV libraryimport cv2 import os, math, operator from PIL import Image from functools import reduce ###Call the computer camera to detect faces and take screenshots def CatchPICFromVideo(window_name, path_name): (window_name) #Computer Camera cap = (0) #Tell OpenCV to use the face recognition classifier classfier = ( + "haarcascade_frontalface_default.xml") #Click the color of the border to be drawn after the face is detected color = (0, 255, 0) while (): ok, frame = () #Read a frame of data if not ok: break grey = (frame, cv2.COLOR_BGR2GRAY) #Convert the current frame image to grayscale image #Face detection, 1.2 and 2 are the picture scaling ratio and the number of valid points to be detected respectively faceRects = (grey, scaleFactor = 1.2, minNeighbors = 3, minSize = (32, 32)) if len(faceRects) > 0: #Any than 0 face is detected for faceRect in faceRects: #Frame each face individually x, y, w, h = faceRect #Draw a rectangular frame (frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2) k = (100) #Read the keyboard every 0.1 seconds if k == ord("z") or k == ord("Z"): #If you enter z #Save the current frame as an image img_name = path_name print(img_name) image = frame[y - 10: y + h + 10, x - 10: x + w + 10] (img_name, image,[int(cv2.IMWRITE_PNG_COMPRESSION), 9]) break #Show images (window_name, frame) #Exit the camera interface c = (100) if c == ord("q") or c == ord("Q"): break #Release the camera and destroy all windows () () ("cls") #New official websiterecogname = "" #Pre-saved face filesCatchPICFromVideo("get face",recogname)
Function:
Although it can frame the face, the efficiency is not very high.
Press Z or z to capture and save the framed face
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.