Face Detection Using Python and OpenCV
Hello friend, in this post we will create a "Face Detection" program using the OpenCV library using the Python programming language. "Face Detection" is a program that can recognize a face in a frame, be it in the form of images or videos. One use of this technique is the attendance process carried out in an agency so that there is no forgery of attendance.
First, open your editor, here I use PyCharm then create a file named "index.py". When done, make sure you already have the file "haarcascade_frontalface_default.xml" if you don't have it, please download here and put it in the same folder as "index.py"
Open index.py and enter the following code
import cv2 faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") cam = cv2.VideoCapture(0)
First, we import the OpenCV library, then we load the haarcascade_frontalface_default.xml file into the "faceCascade" variable, then activate the camera loaded in the "cam" variable
Note : If you use an external camera, please change cv2.VideoCapture (0) to cv2.VideoCapture (1)
Next, enter the code below
while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, 1.2,5)
The above code serves to do continuous looping on the code inside
- Every frame taken using an external webcam or camera is entered into the variable "im"
- Converting to Gray mode variable "im"
- Detect all faces in the frame
Next, enter the following code
for(x,y,w,h) in faces: cv2.rectangle(im, (x-20,y-20), (x+w+20, y+h+20), (0,255,0), 4) cv2.imshow('Face Detection', im)
The code above serves to make a green box in the face area that is detected in the frame. Then display in a new window with the name "Face Detection". When finished, enter the following closing code so that the window still appears.
if cv2.waitKey(10) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()
At this point, the program is ready to run.
Full Source Code :
import cv2 faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") cam = cv2.VideoCapture(0) while True: ret, im = cam.read() gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, 1.2,5) for(x,y,w,h) in faces: cv2.rectangle(im, (x-20,y-20), (x+w+20, y+h+20), (0,255,0), 4) cv2.imshow('Face Detection', im) if cv2.waitKey(10) & 0xFF == ord('q'): break cam.release() cv2.destroyAllWindows()