0 points

Face Detection using OpenCV


dashboard

Sun Jun 07 2020 02:45:42 GMT+0000 (UTC)

Posted by @biranchi125 #python

A) Detect faces in Image file (using Python & OpenCV)



face_detect.py :
=================

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

img = cv2.imread('face.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)


faces = face_cascade.detectMultiScale(
    gray,
    scaleFactor=1.1,
    minNeighbors=5,
    minSize=(30, 30),
    flags = cv2.CASCADE_SCALE_IMAGE
)

print("Faces shape : ", faces.shape)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

print("Face count : ", faces.shape[0])

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


=====================================================================

B) Detect faces using Camera (using Python & OpenCV).


face_detect_cam.py :
====================
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)

while True:
	ret, img = cap.read();
	
	if not ret:
		break
		
	gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

	faces = face_cascade.detectMultiScale(
		gray,
		scaleFactor=1.1,
		minNeighbors=5,
		minSize=(30, 30),
		flags = cv2.CASCADE_SCALE_IMAGE
	)

	for (x,y,w,h) in faces:
		cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
	
	cv2.imshow('Face', img)
	
	key = cv2.waitKey(1)
	if key==27 or key==ord('q'):
		break;

cap.release()
cv2.destroyAllWindows()


content_copy Copy

Detect faces from Image or using Camera Requirements : 1. Python3 2. OpenCV Files required: ---------------- 1. haarcascade_frontalface_default.xml (Download the xml file from https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml) 2. Add any .jpg/.png file containing human faces (For face detection from Image file)