Advertisement
dan-masek

Face Recognition Test - r1

Mar 27th, 2016
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.26 KB | None | 0 0
  1. import logging
  2. import logging.handlers
  3. import os
  4. import time
  5. import sys
  6.  
  7. import cv2
  8. import numpy as np
  9.  
  10. # ============================================================================
  11.  
  12. CASCADE_FILENAME = 'data/haarcascade_frontalface_alt.xml'
  13. MASK_FILENAME = 'data/mask.png'
  14.  
  15. IMAGE_DIR = "images"
  16. IMAGE_FILENAME_FORMAT = IMAGE_DIR + "/frame_%04d.png"
  17.  
  18. # Support either live acquisition or replay of saved frames
  19. CAPTURE_FROM_CAMERA = True
  20. if CAPTURE_FROM_CAMERA:
  21.     IMAGE_SOURCE = 0 # Default camera
  22. else:
  23.     IMAGE_SOURCE = IMAGE_FILENAME_FORMAT # Image sequence
  24.  
  25. # Time to wait between frames, 0=forever
  26. WAIT_TIME = 2500 # ms
  27.  
  28. SCALING_FACTOR = 0.5
  29.  
  30. LOG_TO_FILE = False
  31.  
  32. # ============================================================================
  33.  
  34. def init_logging():
  35.     main_logger = logging.getLogger()
  36.  
  37.     formatter = logging.Formatter(
  38.         fmt='%(asctime)s.%(msecs)03d %(levelname)-8s [%(name)s] %(message)s'
  39.         , datefmt='%Y-%m-%d %H:%M:%S')
  40.    
  41.     handler_stream = logging.StreamHandler(sys.stdout)
  42.     handler_stream.setFormatter(formatter)
  43.     main_logger.addHandler(handler_stream)
  44.    
  45.     if LOG_TO_FILE:
  46.         handler_file = logging.handlers.RotatingFileHandler("debug.log"
  47.             , maxBytes = 2**24
  48.             , backupCount = 10)
  49.         handler_file.setFormatter(formatter)
  50.         main_logger.addHandler(handler_file)
  51.    
  52.     main_logger.setLevel(logging.DEBUG)
  53.    
  54.     return main_logger
  55.  
  56. # ============================================================================
  57.  
  58. def process_frame(frame_number, frame, face_cascade, face_mask, scaling_factor):
  59.     log = logging.getLogger("process_frame")
  60.    
  61.     resized_frame = cv2.resize(frame
  62.         , None
  63.         , fx=scaling_factor
  64.         , fy=scaling_factor
  65.         , interpolation=cv2.INTER_AREA)
  66.     log.debug("Resized frame: shape=%s", resized_frame.shape)
  67.    
  68.     # Let's make a copy to draw into
  69.     processed_frame = resized_frame.copy()
  70.    
  71.     grayscale_frame = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2GRAY)
  72.  
  73.     CASCADE_SCALE_FACTOR = 1.3
  74.     CASCADE_MIN_NEIGHBORS = 5
  75.    
  76.     log.debug("Detecting faces...")
  77.     face_rects = face_cascade.detectMultiScale(grayscale_frame
  78.         , scaleFactor=CASCADE_SCALE_FACTOR
  79.         , minNeighbors=CASCADE_MIN_NEIGHBORS)
  80.     log.debug("Got %d matches.", len(face_rects))
  81.    
  82.     for (i, face_rect) in enumerate(face_rects):
  83.         (x,y,w,h) = face_rect
  84.         log.debug("Match #%d: pos=(x=%d, y=%d) size=(w=%d, h=%d)", i, x, y, w, h)
  85.        
  86.         if (h <= 0) or (w <= 0):
  87.             log.debug("Invalid match size, skipping.")
  88.             continue
  89.        
  90.         # Q: What's the reason for this?
  91.         h2 = int(1.4 * h)
  92.         w2 = int(1.0 * w)
  93.         y2 = y - 0.1 * h
  94.         x2 = x
  95.         log.debug("Scaled bounding box: pos=(x=%d, y=%d) size=(w=%d, h=%d)", x2, y2, w2, h2)
  96.        
  97.         frame_roi = processed_frame[y2:y2+h2, x2:x2+w2]
  98.         log.debug("Frame ROI: shape=%s", frame_roi.shape)
  99.        
  100.         resized_face_mask = cv2.resize(face_mask, (w2, h2), interpolation=cv2.INTER_AREA)
  101.         log.debug("Resized face mask: shape=%s", resized_face_mask.shape)
  102.         grayscale_face_mask = cv2.cvtColor(resized_face_mask, cv2.COLOR_BGR2GRAY)
  103.        
  104.         ret, mask = cv2.threshold(grayscale_face_mask, 180, 255, cv2.THRESH_BINARY_INV)
  105.         mask_inv = cv2.bitwise_not(mask)
  106.        
  107.         masked_face = cv2.bitwise_and(resized_face_mask, resized_face_mask, mask=mask)
  108.         masked_frame = cv2.bitwise_and(frame_roi, frame_roi, mask=mask_inv)
  109.        
  110.         processed_frame[y2:y2+h2, x2:x2+w2] = cv2.add(masked_face, masked_frame)
  111.        
  112.     return processed_frame
  113.  
  114. # ============================================================================
  115.  
  116. def main():
  117.     log = logging.getLogger("main")
  118.    
  119.     # Create the cascade classifier
  120.     log.debug("Loading cascade classifier `%s`...", CASCADE_FILENAME)
  121.     face_cascade = cv2.CascadeClassifier(CASCADE_FILENAME)
  122.     if face_cascade.empty():
  123.         raise IOError('Unable to load the face cascade classifier xml file')
  124.  
  125.     # Load and prepare the face mask
  126.     log.debug("Loading face mask `%s`...", MASK_FILENAME)
  127.     face_mask = cv2.imread(MASK_FILENAME)
  128.     if face_mask is None:
  129.         raise IOError('Unable to load the face mask image')
  130.     log.debug("Face mask loaded, shape=%s", face_mask.shape)
  131.  
  132.     # Set up image source
  133.     log.debug("Initializing video capture device #%d...", IMAGE_SOURCE)
  134.     cap = cv2.VideoCapture(IMAGE_SOURCE)
  135.    
  136.     frame_width = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
  137.     frame_height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
  138.     log.debug("Video capture frame size=(w=%d, h=%d)", frame_width, frame_height)
  139.        
  140.     log.debug("Starting capture loop...")
  141.     frame_number = -1
  142.     while True:
  143.         frame_number += 1
  144.         log.debug("Capturing frame #%d...", frame_number)
  145.         ret, frame = cap.read()
  146.         if not ret:
  147.             log.error("Frame capture failed, stopping...")
  148.             break
  149.  
  150.         log.debug("Got frame #%d: shape=%s", frame_number, frame.shape)
  151.        
  152.         # Archive raw frames from camera to disk, so we can play them back later
  153.         if CAPTURE_FROM_CAMERA:
  154.             file_name = IMAGE_FILENAME_FORMAT % frame_number
  155.             log.debug("Saving frame #%d as '%s'", frame_number, file_name)
  156.             cv2.imwrite(file_name, frame)
  157.            
  158.         log.debug("Processing frame #%d...", frame_number)
  159.         processed = process_frame(frame_number, frame, face_cascade, face_mask, SCALING_FACTOR)
  160.  
  161.         cv2.imshow('Source Image', frame)
  162.         cv2.imshow('Processed Image', processed)
  163.        
  164.         log.debug("Frame #%d processed.", frame_number)
  165.        
  166.         c = cv2.waitKey(WAIT_TIME)
  167.         if c == 27:
  168.             log.debug("ESC detected, stopping...")
  169.             break
  170.  
  171.     log.debug("Closing video capture device...")
  172.     cap.release()
  173.     cv2.destroyAllWindows()
  174.     log.debug("Done.")
  175.  
  176. # ============================================================================
  177.  
  178. if __name__ == "__main__":
  179.     log = init_logging()
  180.    
  181.     if not os.path.exists(IMAGE_DIR):
  182.         log.debug("Creating image directory `%s`...", IMAGE_DIR)
  183.         os.makedirs(IMAGE_DIR)
  184.    
  185.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement