import cv2
face_cascade = cv2. CascadeClassifier( cv2. data. haarcascades + 'haarcascade_frontalface_default.xml' )
cap = cv2. VideoCapture( 0 )
prev_faces = [ ]
def draw_rounded_rectangle ( img, x, y, w, h, radius, color, thickness) :
cv2. line( img, ( x + radius, y) , ( x + w - radius, y) , color, thickness)
cv2. line( img, ( x + radius, y + h) , ( x + w - radius, y + h) , color, thickness)
cv2. line( img, ( x, y + radius) , ( x, y + h - radius) , color, thickness)
cv2. line( img, ( x + w, y + radius) , ( x + w, y + h - radius) , color, thickness)
cv2. ellipse( img, ( x + radius, y + radius) , ( radius, radius) , 180 , 0 , 90 , color, thickness)
cv2. ellipse( img, ( x + w - radius, y + radius) , ( radius, radius) , 270 , 0 , 90 , color, thickness)
cv2. ellipse( img, ( x + w - radius, y + h - radius) , ( radius, radius) , 0 , 0 , 90 , color, thickness)
cv2. ellipse( img, ( x + radius, y + h - radius) , ( radius, radius) , 90 , 0 , 90 , color, thickness)
def smooth_faces ( faces, prev_faces= None , alpha= 0 ) :
if prev_faces is None or len ( prev_faces) == 0 :
return faces
smoothed_faces = [ ]
for ( x, y, w, h) in faces:
found = False
for ( prev_x, prev_y, prev_w, prev_h) in prev_faces:
if x - 30 <= prev_x <= x + 30 and y - 30 <= prev_y <= y + 30 :
smoothed_x = int ( alpha * x + ( 1 - alpha) * prev_x)
smoothed_y = int ( alpha * y + ( 1 - alpha) * prev_y)
smoothed_w = int ( alpha * w + ( 1 - alpha) * prev_w)
smoothed_h = int ( alpha * h + ( 1 - alpha) * prev_h)
smoothed_faces. append( ( smoothed_x, smoothed_y, smoothed_w, smoothed_h) )
found = True
break
if not found:
smoothed_faces. append( ( x, y, w, h) )
return smoothed_faces
no_face_count = 0
max_no_face_count = 100
while True :
ret, frame = cap. read( )
if not ret:
break
gray = cv2. cvtColor( frame, cv2. COLOR_BGR2GRAY)
faces = face_cascade. detectMultiScale( gray, scaleFactor= 1.1 , minNeighbors= 5 , minSize= ( 30 , 30 ) )
faces = list ( faces)
faces = smooth_faces( faces, prev_faces, alpha= 0.3 )
prev_faces = faces. copy( )
if len ( faces) > 0 :
for ( x, y, w, h) in faces:
radius = int ( min ( w, h) / 10 )
draw_rounded_rectangle( frame, x, y, w, h, radius, ( 18 , 153 , 255 ) , 2 )
text = "Face"
font = cv2. FONT_HERSHEY_SIMPLEX
font_scale = 0.8
thickness = 2
text_size, _ = cv2. getTextSize( text, font, font_scale, thickness)
text_x = x + int ( ( w - text_size[ 0 ] ) / 2 )
text_y = y - 10
cv2. putText( frame, text, ( text_x, text_y) , font, font_scale, ( 18 , 153 , 255 ) , thickness, cv2. LINE_AA)
cv2. imshow( 'Face Detection' , frame)
if cv2. waitKey( 1 ) == 27 :
break
cap. release( )
cv2. destroyAllWindows( )