Advertisement
metalx1000

OpenCV Face Detection with Python

Mar 6th, 2023
1,770
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # http://creatingwithcode.com/howto/face-detection-in-static-images-with-python/
  4. # sudo apt-get install python-opencv libcv-dev opencv-doc
  5. # face_detect.py
  6.  
  7. # Face Detection using OpenCV. Based on sample code from:
  8. # http://python.pastebin.com/m76db1d6b
  9.  
  10. # Usage: python face_detect.py <image_file>
  11.  
  12. import sys, os
  13. from opencv.cv import *
  14. from opencv.highgui import *
  15. import Image, ImageDraw
  16.  
  17. def detectObjects(image):
  18.   """Converts an image to grayscale and prints the locations of any
  19.     faces found"""
  20.   grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1) # 8 is depth and 1 is channels
  21.   cvCvtColor(image, grayscale, CV_BGR2GRAY)
  22.  
  23.   storage = cvCreateMemStorage(0)
  24.   cvClearMemStorage(storage)
  25.   cvEqualizeHist(grayscale, grayscale)
  26.   cascade = cvLoadHaarClassifierCascade('/usr/share/doc/opencv-doc/examples/haarcascades/haarcascades/haarcascade_frontalface_default.xml.gz', cvSize(1,1))
  27.   faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.2, 2, CV_HAAR_DO_CANNY_PRUNING, cvSize(50,50))
  28.  
  29.   if faces.total > 0:
  30.     for f in faces:
  31.         print("[(%d,%d) -> (%d,%d)]" % (f.x, f.y, f.x+f.width, f.y+f.height))
  32.         x1,y1,x2,y2=f.x,f.y,f.x+f.width,f.y+f.height
  33.         print_rectangle(x1,y1,x2,y2) #call to a python pil
  34.  
  35. def print_rectangle(x1,y1,x2,y2): #function to modify the img
  36.     im = Image.open(sys.argv[1])
  37.     draw = ImageDraw.Draw(im)
  38.     draw.rectangle([x1,y1,x2,y2])
  39.     im.save(sys.argv[1])
  40.  
  41. def main():
  42.   image = cvLoadImage(sys.argv[1])
  43.   detectObjects(image)
  44.  
  45. if __name__ == "__main__":
  46.   main()
  47.  
  48.  
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement