Guest User

human detect

a guest
Feb 26th, 2019
139
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # USAGE
  2. # python pi_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
  3.  
  4. from multiprocessing import Process, Queue
  5. from imutils.video import FPS
  6. import numpy as np
  7. import argparse
  8. import imutils
  9. import datetime
  10. import time
  11. import cv2
  12.  
  13. def classify_frame(net, inputQueue, outputQueue):
  14.     print("[INFO] starting classify process...")
  15.     while True:
  16.         if not inputQueue.empty():
  17.             frame = inputQueue.get()
  18.             frame = cv2.resize(frame, (300, 300))
  19.             blob = cv2.dnn.blobFromImage(frame, 0.007843, (300, 300), 127.5)
  20.    
  21.             net.setInput(blob)
  22.             detections = net.forward()
  23.    
  24.             outputQueue.put(detections)
  25.         time.sleep(2)
  26.  
  27. def write_frame(writeQueue, startQueue):
  28.     print("[INFO] starting write process...")
  29.     fourcc = cv2.VideoWriter_fourcc('M','J','P','G') #*'MJPG'
  30.     out = cv2.VideoWriter('output.avi', fourcc, 20, (640, 480), True)
  31.    
  32.     while True:
  33.         if not writeQueue.empty():
  34.             frame = writeQueue.get()
  35.             out.write(frame)
  36.     out.release()
  37.    
  38. ap = argparse.ArgumentParser()
  39. ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file")
  40. ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model")
  41. args = vars(ap.parse_args())
  42.  
  43. CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
  44.     "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
  45.     "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
  46.     "sofa", "train", "tvmonitor"]
  47. COLORS = np.random.uniform(0, 255, size=(len(CLASSES), 3))
  48.  
  49. inputQueue = Queue(maxsize=1)
  50. outputQueue = Queue(maxsize=1)
  51. writeQueue = Queue(maxsize=1)
  52. startQueue = Queue(maxsize=1)
  53.  
  54. detections = None
  55. confidence_set = 0.8
  56. count = 0
  57.  
  58. print("[INFO] loading model...")
  59. net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])
  60.  
  61. print("[INFO] starting process...")
  62. p = Process(target=classify_frame, args=(net, inputQueue, outputQueue,))
  63. p.daemon = True
  64. p.start()
  65. w = Process(target=write_frame, args=(writeQueue, startQueue))
  66. w.daemon = True
  67. w.start()
  68.  
  69. print("[INFO] starting video stream...")
  70. vs = cv2.VideoCapture(0)
  71. fps = FPS().start()
  72.  
  73. global fW, fH, framerate
  74. fW = vs.get(3)
  75. print ("[INFO] fW:", fW)
  76. fH = vs.get(4)
  77. print ("[INFO] fH:", fH)
  78. framerate = vs.get(5)
  79. print ("[INFO] ramerate:", framerate)
  80.  
  81. while True:
  82.     ret, frame = vs.read()
  83.     if ret == True:    
  84.         if inputQueue.empty():
  85.             inputQueue.put(frame)
  86.         if not outputQueue.empty():
  87.             detections = outputQueue.get()
  88.        
  89.         cv2.putText(frame, datetime.datetime.now().strftime("%c"), (10, 25), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0,255,0), 1)
  90.        
  91.         if detections is not None:
  92.             for i in np.arange(0, detections.shape[2]):
  93.                 confidence = detections[0, 0, i, 2]
  94.    
  95.                 if confidence > confidence_set:
  96.                        
  97.                     idx = int(detections[0, 0, i, 1])
  98.                    
  99.                     label = "{}: {:.2f}%".format(CLASSES[idx], confidence * 100)
  100.                    
  101.                     if idx == 8 or idx == 12 or idx == 15:
  102.                         print(label)
  103.                         count = 100
  104.  
  105.         if count > 1:# счетчик для записи кадров после пропадания объекта из кадра
  106.             writeQueue.put(frame)
  107.             count -= 1
  108.             print(count)
  109.         cv2.imshow("Camera", frame)
  110.         key = cv2.waitKey(1) & 0xFF
  111.         if key == ord("q"):
  112.             break
  113.     else:
  114.         break
  115.     fps.update()
  116.  
  117. fps.stop()
  118. vs.release()
  119. print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
  120. print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
  121. cv2.destroyAllWindows()
RAW Paste Data