Face Detection Script in Python

Method # 1

import cv2 #pip install opencv-python
import pathlib # take the cascade file for frontal face detection cascade_path = pathlib.Path(cv2.__file__).parent.absolute()/"data/haarcascade_frontalface_default.xml" # print(cascade_path) # training classifier on the cascade file clf = cv2.CascadeClassifier(str(cascade_path)) # face detection in camera camera = cv2.VideoCapture(0) # 0 is for default camera # face detection in video # camera = cv2.VideoCapture("cud.mp4") while True: _, frame = camera.read() # _ ignores the first return value # some Python functions return multiple values, often we don’t need all of them. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = clf.detectMultiScale( gray, scaleFactor = 1.1, minNeighbors=5, # higher this number, less faces are found minSize = (30, 30), # size of window flags = cv2.CASCADE_SCALE_IMAGE) # plotting rectangle around faces for (x,y,width,height) in faces: cv2.rectangle(frame, (x, y), (x+width, y+height), (0,255,255), 2) # 2 is thickness # show the frame with title "Faces" cv2.imshow("Faces", frame) # to close the frame if cv2.waitKey(1) == ord("q"): break camera.release() cv2.destroyAllWindows()
Method # 2
    
import cv2 #pip install opencv-python

face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# "haarcascade_frontalface_default.xml" files resides in same folder as .py file

img = cv2.imread("me.jpg")

# now convert the image to gray-scale so it is readable
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, 1.1, 4,)

for (x,y,w,h) in faces:
      cv2.rectangle(img, (x, y), (x+w, y+h), (255, 225, 0), 2)
      
cv2.imshow("My Image", img)
cv2.waitKey() # upon any key pressed, exits

cv2.imwrite("abdur_face_detected.jpg", img) # saves image with face detected
  
    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes