baotrung217

emotion_detection_v2_multithread

Apr 22nd, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.57 KB | None | 0 0
  1. from picamera.array import PiRGBArray
  2. from picamera import PiCamera
  3. from multiprocessing import Process
  4. from multiprocessing import Queue
  5. import time
  6. import cv2
  7. import numpy as np
  8. import tensorflow as tf
  9. import sys
  10.  
  11. DEBUG = True
  12.  
  13. # instanciate the camera
  14. camera = PiCamera()
  15. camera.resolution = (1920, 1080)
  16. camera.framerate = 30
  17. rawCapture = PiRGBArray(camera, size=(1920, 1080))
  18.  
  19. # allow the camera to warmup
  20. time.sleep(0.1)
  21.  
  22. # Loads label file, strips off carriage return
  23. label_lines = [line.rstrip() for line
  24.                    in tf.gfile.GFile("./retrained_data/retrained_labels.txt")]
  25. # load our pretrained model
  26. with tf.gfile.FastGFile("./retrained_data/retrained_graph.pb", 'rb') as f:
  27.     graph_def = tf.GraphDef()
  28.     graph_def.ParseFromString(f.read())
  29.     _ = tf.import_graph_def(graph_def, name='')
  30.  
  31. # We use the Haar Cascade classifier
  32. faceDetect = cv2.CascadeClassifier('./retrained_data/haarcascade_frontalface_default.xml')
  33.  
  34.  
  35. def prediction_fn(model, inputQueue, outputQueue, label_lines):
  36.     while True:
  37.         if not inputQueue.empty():
  38.             # grab the frame from the input queue          
  39.             input_image = inputQueue.get()
  40.            
  41.             # make the prediction
  42.             # feed the detected face (cropped image) to the tf graph
  43.             predictions = sess.run(model, {'DecodeJpeg:0': input_image})
  44.             prediction = predictions[0]
  45.  
  46.             # Get the highest confidence category.
  47.             prediction = prediction.tolist()
  48.             max_value = max(prediction)
  49.             max_index = prediction.index(max_value)
  50.             predicted_label = label_lines[max_index]
  51.  
  52.             print("%s (%.2f%%)" % (predicted_label, max_value * 100))
  53.             # write the detections to the output queue
  54.             outputQueue.put(predicted_label)
  55.  
  56. # start the tensorflow session and start streaming and image processing
  57. sess = tf.Session()
  58. softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
  59.  
  60. # initialize the input queue (detected faces grayed), output queue (predictions),
  61. inputQueue = Queue(maxsize=1)
  62. outputQueue = Queue(maxsize=1)
  63. predictions = None
  64.  
  65. # initialize the prediction process
  66. p = Process(target=prediction_fn, args=(softmax_tensor, inputQueue,
  67.     outputQueue,label_lines,))
  68. p.daemon = True
  69. p.start()
  70.  
  71.  
  72. # capture frames from the camera
  73. for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
  74.    
  75.     # transform into a numpy array
  76.     image = frame.array
  77.     # show the frame
  78.     cv2.imshow("face", image)
  79.     if DEBUG:
  80.         print (image.shape)
  81.     # transform to Gray scale
  82.     gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  83.     if DEBUG:
  84.         print (gray.shape)
  85.     # detect faces in our gray picture
  86.     faces = faceDetect.detectMultiScale(gray,
  87.                                         scaleFactor=1.3,
  88.                                         minNeighbors=5
  89.                                         )
  90.  
  91.  
  92.     for (x,y,w,h) in faces:
  93.         # if our input queue is empty we pile one detected face for prediction
  94.         if inputQueue.empty():
  95.             inputQueue.put(gray[y:y+h,x:x+w])
  96.  
  97.         # if there is a prediction in the output queue, we grab it
  98.         if not outputQueue.empty():
  99.             predictions = outputQueue.get()
  100.  
  101.         cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2)
  102.         cv2.waitKey(100)
  103.  
  104.     key = cv2.waitKey(1) & 0xFF
  105.  
  106.     # clear the stream in preparation for the next frame
  107.     rawCapture.truncate(0)
  108.  
  109.     # if the `q` key was pressed, break from the loop
  110.     if key == ord("q"):
  111.         cv2.destroyAllWindows()
  112.         break
Advertisement
Add Comment
Please, Sign In to add comment