Face Recognition
We will do face recognition in this article using something known as haar cascades. Haar Cascade is a machine learning-based approach where a lot of positive and negative images are used to train the classifier.
- Positive images: These images contain the images which we want our classifier to identify.
- Negative Images: Images of everything else, which do not contain the object we want to detect.
File Used:
- haarcascade_frontalface_default.xml
- haarcascade_eye.xml
Example: Python OpenCV Face Recognition
Python3
# OpenCV program to detect face in real time # import libraries of python OpenCV # where its functionality resides import cv2 # Trained XML classifiers describes some features of some # object we want to detect a cascade function is trained # from a lot of positive(faces) and negative(non-faces) # images. face_cascade = cv2.CascadeClassifier( 'haarcascade_frontalface_default.xml' ) # Trained XML file for detecting eyes eye_cascade = cv2.CascadeClassifier( 'haarcascade_eye.xml' ) # capture frames from a camera cap = cv2.VideoCapture( 0 ) # loop runs if capturing has been initialized. while 1 : # reads frames from a camera ret, img = cap.read() # convert to gray scale of each frames gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detects faces of different sizes in the input image faces = face_cascade.detectMultiScale(gray, 1.3 , 5 ) for (x,y,w,h) in faces: # To draw a rectangle in a face cv2.rectangle(img,(x,y),(x + w,y + h),( 255 , 255 , 0 ), 2 ) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] # Detects eyes of different sizes in the input image eyes = eye_cascade.detectMultiScale(roi_gray) # To draw a rectangle in eyes for (ex,ey,ew,eh) in eyes: cv2.rectangle(roi_color,(ex,ey),(ex + ew,ey + eh),( 0 , 127 , 255 ), 2 ) # Display an image in a window cv2.imshow( 'img' ,img) # Wait for Esc key to stop k = cv2.waitKey( 30 ) & 0xff if k = = 27 : break # Close the window cap.release() # De-allocate any associated memory usage cv2.destroyAllWindows() |
Output
Getting Started with Python OpenCV
Computer Vision is one of the techniques from which we can understand images and videos and can extract information from them. It is a subset of artificial intelligence that collects information from digital images or videos.
Python OpenCV is the most popular computer vision library. By using it, one can process images and videos to identify objects, faces, or even handwriting of a human. When it is integrated with various libraries, such as NumPy, python is capable of processing the OpenCV array structure for analysis.
In this article, we will discuss Python OpenCV in detail along with some common operations like resizing, cropping, reading, saving images, etc with the help of good examples.