Face detection function
In OpenCV, using the face detection function is cv2 CascadeClassifier. DetectMultiScale (), it can detect all the faces in the image. Its full definition is as follows:
def detectMultiScale(self, image, scaleFactor=None, minNeighbors=None, flags=None, minSize=None, maxSize=None) :
Copy the code
Image: the image to be detected, usually a gray image
ScaleFactor: Indicates the scale of the search window in two successive scans
MinNeighbors: indicates the minimum number of adjacent rectangles that constitute the detection target. The default value is 3, indicating that there are more than 3 detection marks exist, only the existence of the face. If you want to improve the accuracy of detection, you can set the value to a larger value, but at the same time, some faces may not be detected
Flags: this parameter is not commonly used and is generally omitted.
MinSize: The minimum size of the target. Targets smaller than this size are ignored
MaxSize: The maximum size of the target. Targets larger than this size are ignored
The return value of this function is the rectangular box vector set of the target object.
Detect N faces in the image
Now that we know about face detection functions. Below, we will use it to detect the face in the image, the specific code is as follows:
import cv2
img = cv2.imread("41.jpg")
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.15, minNeighbors=2, minSize=(5.5))
print(faces)
print("There are {0} human faces in this picture.".format(len(faces)))
for (x, y, w, h) in faces:
cv2.circle(img, (int((2 * x + w) / 2), int((2 * y + h) / 2)), int(w / 2), (0.255.0), 2)
cv2.imshow("result", img)
cv2.waitKey()
cv2.destroyAllWindows()
Copy the code
OpenCV has its own face Haar feature classifier, which has more than 20 kinds of objects, providing detection functions, such as nose, ears and so on. Here we choose the haarCascade_frontalface_default.xml face recognition classifier.
DetectMultiScale function returns the rectangular frame vector group of the face, including the upper-left coordinates (x, Y), length and width (W, H). And draw face circular box only need to set the center of the rectangle as the center of the circle, the width of the rectangle is generally set as the radius.
After running, we can recognize faces in images of walking dead