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()
Comments