Advertisement
natym

Rectangle Faces

Jun 16th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.64 KB | None | 0 0
  1. #!/usr/bin/env python2
  2. # -*- coding: utf-8 -*- #
  3.  
  4. from twitterbot import TwitterBot
  5. from picbot import PicBot
  6. from PIL import Image, ImageDraw
  7. from sys import argv
  8.  
  9. import numpy
  10. import cv2
  11.  
  12. import keys
  13.  
  14.  
  15. classifier = "haarcascade_frontalface_default.xml"
  16. faceCascade = cv2.CascadeClassifier(classifier)
  17.  
  18.  
  19. def face_detect(image):
  20.     """
  21.     Return rectangles of identified face regions
  22.     """
  23.  
  24.     # numpy grayscale image for face detection
  25.     array = numpy.asarray(image)
  26.     gray_image = cv2.cvtColor(array, cv2.COLOR_BGR2GRAY)
  27.  
  28.     # tweak this for better results ..
  29.  
  30.     faces = faceCascade.detectMultiScale(
  31.         gray_image,
  32.         scaleFactor=1.1,
  33.         minNeighbors=5,
  34.         minSize=(30, 30),
  35.         flags=cv2.cv.CV_HAAR_SCALE_IMAGE
  36.     )
  37.  
  38.     # convert boxes from from arrays to tuples
  39.     boxes = [(x, y, x + w, y + h) for (x, y, w, h) in faces]
  40.     return boxes
  41.        
  42.  
  43. HORIZONTAL = Image.FLIP_TOP_BOTTOM
  44. VERTICAL = Image.FLIP_LEFT_RIGHT
  45.  
  46.  
  47.  
  48. def face_rectangle(image):
  49.     """
  50.     Make white rectangle over the eyes
  51.     """
  52.  
  53.     # work on a copy of the image
  54.     image = image.copy()
  55.    
  56.     # face detection with opencv
  57.     boxes = face_detect(image)
  58.  
  59.     # get drawing context for the current image
  60.     ctx = ImageDraw.Draw(image)
  61.  
  62.     # define colors
  63.     white = (255, 255, 255)
  64.  
  65.     # draw boxes
  66.     for box in boxes:
  67.  
  68.         # draw a white box around it
  69.         x1, y1, x2, y2 = box
  70.         box = x1 - 1 , y1 + 10, x2 + 1, y2 - 10
  71.         ctx.rectangle(box, fill=white, outline=None)
  72.  
  73.     return image, boxes
  74.  
  75.  
  76. if __name__ == '__main__':
  77.  
  78.     print("Loading source image")
  79.     src = Image.open("gt.jpg")
  80.     #src.show()
  81.  
  82.     print("Testing face rectangle")
  83.     img, boxes = face_rectangle(src)
  84.     img.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement