Using domestic sources to install faster , Reference tutorial : Zhihu tutorial
Downloaded whl After the document , Press win+R key entry cmd enter , Use the command to transfer the current path to the folder , And then use pip install Command to install .
After installation , So let's test that out openCV Whether it can be used , So you can enter some simple code to test .
import cv2
# Open the under the project folder photo Picture files under subfolders
img = cv2.imread(r'photo\lena.png')
cv2.imshow("lena",img)
cv2.waitKey()
And then run , You can see a pop-up picture window .
There are three steps to detect faces :
1. Open the picture
2. Face detection
3. display picture
you 're right , It's that simple .
Next on the code :
import cv2
# International practice , Open the picture first
img = cv2.imread(r'photo\lena.png')
# Image graying
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Import a file that has stored good face data to recognize faces
face_img = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
# here scaleFactor The parameter is the image zoom ,minNeighbors Is the number of repeated tests for the target
faces = face_img.detectMultiScale(gray_img,scaleFactor=1.05,minNeighbors=5)
# Use rectangle Method to draw a green frame
for x,y,w,h in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
# display picture
cv2.imshow("lena",img)
cv2.waitKey()
complete
The essence of video is picture streaming , Every frame is a picture ,60 Frame video means one second 60 A picture .
Therefore, using the camera for face detection can be modified based on the above code , You only need to detect the face of the pictures captured by the camera one by one and then output it .
import cv2
# Comment out the statement that originally opened the picture , Instead, use getting pictures from the camera
#img = cv2.imread(r'photo\lena.png')
# Turn on the camera . there 0 It refers to the camera to be turned on , There are multiple cameras that can be changed to 1 perhaps 2 wait
cap = cv2.VideoCapture(0)
while True:
# Read information
ret,img = cap.read()
# Detect whether frames are captured
if ret == True:
# Graying
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Face detection
# Import face data
face_img = cv2.CascadeClassifier(r'first/haarcascade_frontalface_default.xml')
# Process the picture
faces = face_img.detectMultiScale(gray_img,scaleFactor=1.05,minNeighbors=5)
# Judge whether the face is obtained , Draw a box if you have one
if len(faces)>0:
for x,y,w,h in faces:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
# Output
cv2.imshow('capture',img)
# Wait for keyboard input , If the input is q, And then jump out of the loop , end
if cv2.waitKey(30) & 0xFF == ord('q'):
break
else:
break
# Release resources , close window
cap.release()
cv2.destroyAllWindows()