A brief introduction to OpenCV

OpenCV installation, using PIP installation, recommended to use Tsinghua source, fast:

pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
Copy the code

Another module is required:

pip install opencv-contrib-python -i https://pypi.tuna.tsinghua.edu.cn/simple
Copy the code

Now you can learn about OpenCV.

1.1. OpenCv displays images

Simply read an image and display it:

 

Im = cv2.imread('./ ZXC /1.jpg') Cv2.imshow ('im', im) # wait for keyboard input, passing in the millisecond value, when 0 is passed, indicating infinite wait. Cv2.waitkey (0) # Since OpenCv is written in C/C++, let go of the memory cv2.DestroyallWindows ()Copy the code

The above code will achieve the simplest read and display image operation.

1.2. Opencv image grayscale conversion

Grayscale conversion is the conversion of a picture to a black and white image. Because we are in face recognition, gray image is easy to recognize,

Import cv2 # import cv2 # import image im = cv2.imread('./ ZXC /2.jpg') # import cv2 # import image im = cv2.imread('./ ZXC /2.jpg') Return an ndarray object grey = cv2.cvtcolor (im, cv2.color_bgr2gray) # Save grey cv2.imwrite('grey.jpg', Cv2.imshow ('grey', grey) # Wait for keyboard input cv2.waitKey(0) # Destroy window Cv2.destroyallWindows ()Copy the code

 

1.3. Draw graphs

In the subsequent detection of the face, we will draw a graph, the face of the frame. Graphics are also very simple to draw.

Import cv2 # import image im = cv2.imread('./ ZXC /15.jpg') # draw rectangle on image im "" Y1) The third argument is the lower-right coordinate (x2, y2) and the fourth argument is the color value, which is in a different order from our previous one, Rectangle (im, (220, 100), (250, 250), (255, 255, 0), 2) # Cv2.waitkey (0) # Destroy window cv2.DestroyallWindows ()Copy the code

Two, face detection

2.1. Obtain characteristic data

Before we can start human testing, we need to get a signature. In the opencV installation directory, the cv2/data folder, after entering this folder, it is full of feature files, we usually choose haarcascade_frontalface_default.xml.

 

2.1. Face detection

We can either copy the feature file to our project or refer to it directly using an absolute path. The cv2.CascadeClassifier object can be used to detect faces

face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
Copy the code

Where, the passed parameter is the path of the feature file. We can take a relative path or we can take an absolute path. The complete human detection code is as follows:

Import cv2# Load feature data face_detector = cv2.CascadeClassifier(' haarCascade_frontalface_default.xml ')# Load image im = Cv2. Imread ('. / ZXC / 2. JPG ') # to detect human face, return to face the location information of faces. = face_detector detectMultiScale (im) # traversal face for x, y, w, h in faces: Rectangle (im, (x, y), (x+w, y+h), (255, 255, 0), 2) im)cv2.waitKey(0)cv2.destroyAllWindows()Copy the code

The detectMultiScale method returns an array object that holds the coordinates of the upper left corner of n faces, the width of the face, and the height of the face. The detection results are as follows:

Three, face recognition

3.1. Training data

The training data mainly consists of two parts, face information and label, where the label is an int list. I have prepared the pictures of Iron Man and Zhou Xingchi in the catalog data. Iron Man is 1 and Zhou Xingchi is 2.

With the image ready, we can start training data with the following code:

import cv2import osimport numpy root_path = "./data/" lables = []faces = [] def getFacesAndLabels(): Global root_path # Obtain face_detector = cv2.cascadeclassifier (' haarCascade_frontalface_default.xml ') Folders = os.listdir(root_path) for Folder in folders: path = os.path.join(root_path, folder) files = os.listdir(path) for file in files: Join (path, file) im = cv2.imread(path1) # Convert grey = cv2.cvtcolor (im, Cv2. COLOR_BGR2GRAY) # read face data face. = face_detector detectMultiScale (grey) for x, y, w, h in the face: # set the tag, Faces. Append (Grey [y:y + h, x:x + w]) return Faces, Lables # calls the method to get the face information and the label Faces, # labels = getFacesAndLabels () to obtain the training object recognizer = cv2. Face. LBPHFaceRecognizer_create (#) training data recognizer. The "train" (faces, Recognizer.write ('model.yml') numpy.array(labels) # Save training data recognizer.write('model.yml')Copy the code

3.2. Face recognition

After we train the data, we can do face recognition. We load training data before identification, and then basic human detection steps. Finally, we call predict method for face recognition and match people in training data.

​​​​​​​​​​​​​​

The import cv2 recognizer = # load training dataset cv2. Face. LBPHFaceRecognizer_create () recognizer. Read ('. / model. Yml ') # im = ready to identify images cv2.imread('10.jpg')grey = cv2.cvtColor(im, Cv2.color_bgr2gray) # Face_detector = cv2.Cascadeclassifier (' haarCascade_frontalface_default.xml ')face = face_detector.detectMultiScale(grey) for x, y, w, h in face: cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 2) label, confidence = recognizer.predict(grey[y:y + h, X :x + w]) print(" %d ": %d "" % (label, confidence)) if confidence > 60: if label == 1: Print (" confidence ") print(" confidence ") elif label == 2: Print (confidence) print(confidence) print(confidence) else Print (" unmatched data ") cv2.imshow('im', im) cv2.waitKey(0) cv2.destroyallWindows ()Copy the code