Smart-Home am Beispiel der Präsenzerkennung im Raum Projektarbeit Lennart Heimbs, Johannes Krug, Sebastian Dohle und Kevin Holzschuh bei Prof. Oliver Hofmann SS2019
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

counter_people.py 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. from imutils.object_detection import non_max_suppression
  2. import numpy as np
  3. import imutils
  4. import cv2
  5. import requests
  6. import time
  7. import argparse
  8. import time
  9. import base64
  10. '''
  11. Usage:
  12. python peopleCounter.py -i PATH_TO_IMAGE # Reads and detect people in a single local stored image
  13. python peopleCounter.py -c # Attempts to detect people using webcam
  14. IMPORTANT: This example is given AS IT IS without any warranty
  15. Made by: Jose Garcia
  16. '''
  17. URL_EDUCATIONAL = "http://things.ubidots.com"
  18. URL_INDUSTRIAL = "http://industrial.api.ubidots.com"
  19. INDUSTRIAL_USER = False # Set this to False if you are an educational user
  20. TOKEN = "A1E-VQSZw6exCjViKRfqHl7ISdrVEm3cG1" # Put here your Ubidots TOKEN
  21. DEVICE = "detector" # Device where will be stored the result
  22. VARIABLE = "people" # Variable where will be stored the result
  23. HOGCV = cv2.HOGDescriptor()
  24. HOGCV.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())
  25. def detector(image):
  26. '''
  27. @image is a numpy array
  28. '''
  29. clone = image.copy()
  30. (rects, weights) = HOGCV.detectMultiScale(image, winStride=(4, 4),
  31. padding=(8, 8), scale=1.05)
  32. # draw the original bounding boxes
  33. for (x, y, w, h) in rects:
  34. cv2.rectangle(clone, (x, y), (x + w, y + h), (0, 0, 255), 2)
  35. # Applies non-max supression from imutils package to kick-off overlapped
  36. # boxes
  37. rects = np.array([[x, y, x + w, y + h] for (x, y, w, h) in rects])
  38. result = non_max_suppression(rects, probs=None, overlapThresh=0.65)
  39. return result
  40. def buildPayload(variable, value, context):
  41. return {variable: {"value": value, "context": context}}
  42. def sendToUbidots(token, device, variable, value, context={}, industrial=True):
  43. # Builds the endpoint
  44. url = URL_INDUSTRIAL if industrial else URL_EDUCATIONAL
  45. url = "{}/api/v1.6/devices/{}".format(url, device)
  46. payload = buildPayload(variable, value, context)
  47. headers = {"X-Auth-Token": token, "Content-Type": "application/json"}
  48. attempts = 0
  49. status = 400
  50. while status >= 400 and attempts <= 5:
  51. req = requests.post(url=url, headers=headers, json=payload)
  52. status = req.status_code
  53. attempts += 1
  54. time.sleep(1)
  55. return req
  56. def argsParser():
  57. ap = argparse.ArgumentParser()
  58. ap.add_argument("-i", "--image", default=None,
  59. help="path to image test file directory")
  60. ap.add_argument("-c", "--camera", default=False,
  61. help="Set as true if you wish to use the camera")
  62. args = vars(ap.parse_args())
  63. return args
  64. def localDetect(image_path):
  65. result = []
  66. image = cv2.imread(image_path)
  67. image = imutils.resize(image, width=min(400, image.shape[1]))
  68. clone = image.copy()
  69. if len(image) <= 0:
  70. print("[ERROR] could not read your local image")
  71. return result
  72. print("[INFO] Detecting people")
  73. result = detector(image)
  74. # shows the result
  75. for (xA, yA, xB, yB) in result:
  76. cv2.rectangle(image, (xA, yA), (xB, yB), (0, 255, 0), 2)
  77. cv2.imshow("result", image)
  78. cv2.waitKey(0)
  79. cv2.destroyAllWindows()
  80. cv2.imwrite("result.png", np.hstack((clone, image)))
  81. return (result, image)
  82. def cameraDetect(token, device, variable, sample_time=5):
  83. cap = cv2.VideoCapture(0)
  84. init = time.time()
  85. # Allowed sample time for Ubidots is 1 dot/second
  86. if sample_time < 1:
  87. sample_time = 1
  88. while(True):
  89. # Capture frame-by-frame
  90. ret, frame = cap.read()
  91. frame = imutils.resize(frame, width=min(400, frame.shape[1]))
  92. result = detector(frame.copy())
  93. # shows the result
  94. #for (xA, yA, xB, yB) in result:
  95. # cv2.rectangle(frame, (xA, yA), (xB, yB), (0, 255, 0), 2)
  96. #cv2.imshow('frame', frame)
  97. # Sends results
  98. if time.time() - init >= sample_time:
  99. #print("[INFO] Sending actual frame results")
  100. # Converts the image to base 64 and adds it to the context
  101. #b64 = convert_to_base64(frame)
  102. #context = {"image": b64}
  103. if len(result):
  104. print("{} people detected.".format(len(result)))
  105. init = time.time()
  106. if cv2.waitKey(1) & 0xFF == ord('q'):
  107. break
  108. # When everything done, release the capture
  109. cap.release()
  110. cv2.destroyAllWindows()
  111. def convert_to_base64(image):
  112. image = imutils.resize(image, width=400)
  113. img_str = cv2.imencode('.png', image)[1].tostring()
  114. b64 = base64.b64encode(img_str)
  115. return b64.decode('utf-8')
  116. def detectPeople(args):
  117. image_path = args["image"]
  118. camera = True if str(args["camera"]) == 'true' else False
  119. # Routine to read local image
  120. if image_path != None and not camera:
  121. print("[INFO] Image path provided, attempting to read image")
  122. (result, image) = localDetect(image_path)
  123. print("[INFO] sending results")
  124. # Converts the image to base 64 and adds it to the context
  125. b64 = convert_to_base64(image)
  126. context = {"image": b64}
  127. print(len(result))
  128. # Sends the result
  129. """req = sendToUbidots(TOKEN, DEVICE, VARIABLE,
  130. len(result), context=context)
  131. if req.status_code >= 400:
  132. print("[ERROR] Could not send data to Ubidots")
  133. return req"""
  134. # Routine to read images from webcam
  135. if camera:
  136. print("[INFO] reading camera images")
  137. cameraDetect(TOKEN, DEVICE, VARIABLE)
  138. def main():
  139. args = argsParser()
  140. detectPeople(args)
  141. if __name__ == '__main__':
  142. main()