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.

253 lines
8.1 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. #!/usr/bin/python3
  2. import pickle
  3. import threading
  4. import sys
  5. import cv2
  6. import os
  7. import numpy as np
  8. from telnetlib import Telnet
  9. from utils import label_map_util
  10. from utils import visualization_utils as vis_util
  11. if sys.platform == "win32":
  12. import tensorflow as tf
  13. from distutils.version import StrictVersion
  14. if StrictVersion(tf.__version__) < StrictVersion('1.12.0'):
  15. raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')
  16. else:
  17. # import psutil
  18. pass
  19. import json
  20. import base64
  21. from PIL import Image
  22. from io import BytesIO
  23. from urllib.parse import urlencode
  24. from urllib.request import Request, urlopen
  25. import ssl
  26. switch = 1
  27. import socket
  28. # This is needed since the notebook is stored in the object_detection folder.
  29. sys.path.append("..")
  30. import time
  31. from object_detection.utils import ops as utils_ops
  32. TELNET = False
  33. AI_IP = '10.10.26.161'
  34. LIGHT_IP = '192.168.2.174'
  35. context = ssl._create_unverified_context()
  36. if TELNET:
  37. tn = Telnet(LIGHT_IP, 31)
  38. light_green = False
  39. # What model to download.
  40. encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
  41. PATH_TO_LABELS = os.path.join('object_detection/data', 'mscoco_label_map.pbtxt')
  42. category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
  43. def load_image_into_numpy_array(image):
  44. (im_width, im_height) = image.size
  45. return np.array(image.getdata()).reshape(
  46. (im_height, im_width, 3)).astype(np.uint8)
  47. data = {"gpu_temp":"10C","gpu_load":"15%","cpu_temp":"47C","cpu_load":"15%","mem_temp":"NaN","mem_load":"17%","fan_speed":"10000RPM"}
  48. """
  49. def get_temps():
  50. global data
  51. if not sys.platform == "win32":
  52. temps = psutil.sensors_temperatures()
  53. data["cpu_temp"] = str(int(temps["dell_smm"][0][1]))+"°C"
  54. data["cpu_load"] = str(psutil.cpu_percent())+"%"
  55. data["mem_load"] = str(dict(psutil.virtual_memory()._asdict())["percent"])+"%"
  56. data["fan_speed"] = str(psutil.sensors_fans()["dell_smm"][0][1])+"RPM"
  57. """
  58. def run_inference_for_single_image(image):
  59. _, buffer = cv2.imencode('.jpg', image)
  60. img_base64 = base64.b64encode(buffer).decode('ascii')
  61. url = 'https://%s:5001/ai' % AI_IP # Set destination URL here
  62. post_fields = {'img': img_base64,"type":"coco"} # Set POST fields here
  63. request = Request(url, urlencode(post_fields).encode())
  64. data = urlopen(request, context=context).read().decode("ascii")
  65. output_dict = json.loads(json.loads(data))
  66. return output_dict
  67. kill = True
  68. def listener(port=8385):
  69. serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  70. serversocket.bind((socket.gethostname(), port))
  71. serversocket.listen(5)
  72. while kill:
  73. serversocket.accept()
  74. print('Bye!')
  75. def lights_on():
  76. global light_green
  77. light_green = True
  78. tn.write(b"1-0")
  79. time.sleep(1)
  80. tn.write(b"2-0")
  81. time.sleep(10)
  82. light_green = False
  83. tn.write(b"0-1")
  84. time.sleep(1)
  85. tn.write(b"0-2")
  86. cut = (150, 250, 250, 150)
  87. cut_send = [0, 0, 0, 0]
  88. img_counter = 0
  89. socket_switch = True
  90. thread = threading.Thread(target=listener)
  91. thread.start()
  92. cam = cv2.VideoCapture(1)
  93. switch = 0
  94. # get_temps()
  95. # (left, right, top, bottom)
  96. ambulance_coordinates = (65, 190, 0, 140)
  97. reps = -1
  98. reps_vid = 0
  99. while 1:
  100. ret,image = cam.read()
  101. image = cv2.imread('/home/efeaydin/Masaüstü/union-county-car-accident-attorneys.jpg')
  102. reps_vid += 1
  103. reps += 1
  104. try: # Kavşak
  105. t1 = time.time()
  106. image_np = image
  107. output_dict = run_inference_for_single_image(image_np)
  108. height, width, channels = image_np.shape
  109. out_dict = {'detection_boxes': [], 'detection_classes': [], 'detection_scores': []}
  110. for index,i in enumerate(output_dict['detection_classes']):
  111. cont = False
  112. if i in [3, 6, 8,44,77]: # Car, bus, truck
  113. score = output_dict['detection_scores'][index]
  114. if score > 0.3:
  115. if not any((output_dict['detection_boxes'][index] == b) for b in out_dict['detection_boxes']):
  116. avg_x = (output_dict['detection_boxes'][index][0] + output_dict['detection_boxes'][index][2])/2
  117. avg_y = (output_dict['detection_boxes'][index][1] + output_dict['detection_boxes'][index][3])/2
  118. for box in out_dict['detection_boxes']:
  119. avg_box_x = (box[0] + box[2])/2
  120. avg_box_y = (box[1] + box[3])/2
  121. if abs(avg_x-avg_box_x) < 0.1 and abs(avg_y-avg_box_y) < 0.1:
  122. cont = True
  123. break
  124. if cont:
  125. continue
  126. out_dict['detection_classes'].append(i)
  127. out_dict['detection_boxes'].append(output_dict['detection_boxes'][index])
  128. out_dict['detection_scores'].append(output_dict['detection_scores'][index])
  129. out_dict['detection_classes'] = np.array(out_dict['detection_classes'])
  130. out_dict['detection_boxes'] = np.array(out_dict['detection_boxes'])
  131. out_dict['detection_scores'] = np.array(out_dict['detection_scores'])
  132. im_height, im_width, _ = image_np.shape
  133. if not light_green and TELNET:
  134. for index, box in enumerate(out_dict['detection_boxes']):
  135. box = tuple(map(int, (box[1] * im_width, box[3] * im_width, box[0] * im_height, box[2] * im_height)))
  136. # (left, right, top, bottom)
  137. if abs((box[0] + box[1])/2 - (ambulance_coordinates[0] + ambulance_coordinates[1])/2) < 25 and \
  138. abs((box[2] + box[3])/2 - (ambulance_coordinates[2] + ambulance_coordinates[3])/2) < 25:
  139. print('ambulance')
  140. threading.Thread(target=lights_on).start()
  141. vis_util.visualize_boxes_and_labels_on_image_array(
  142. image_np,
  143. out_dict['detection_boxes'],
  144. out_dict['detection_classes'],
  145. out_dict['detection_scores'],
  146. category_index,
  147. instance_masks=out_dict.get('detection_masks'),
  148. use_normalized_coordinates=True,
  149. line_thickness=8,
  150. min_score_thresh=0.3
  151. )
  152. cv2.imwrite('/home/efeaydin/Masaüstü/foto.jpg', image_np)
  153. cv2.imshow('frame', image_np)
  154. ex_c = [27, ord("q"), ord("Q")]
  155. if cv2.waitKey(1) & 0xFF in ex_c:
  156. break
  157. t2 = time.time()
  158. print("time taken for {}".format(t2-t1))
  159. if not sys.platform == "win32" and t2-t1 < 0.1:
  160. time.sleep(0.1-(t2-t1))
  161. send_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  162. if socket_switch:
  163. try:
  164. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  165. client_socket.settimeout(0.1)
  166. client_socket.connect(('127.0.0.1', 8485))
  167. connection = client_socket.makefile('wb')
  168. socket_switch = False
  169. except:
  170. socket_switch = True
  171. continue
  172. try:
  173. crop_img = send_image.copy(order='C')
  174. crop_img = Image.fromarray(crop_img, "RGB")
  175. buffered = BytesIO()
  176. crop_img.save(buffered, format="JPEG")
  177. img = base64.b64encode(buffered.getvalue()).decode("ascii")
  178. lens = [len(send_image), 0, len(send_image[0])]
  179. for i in range(0,len(cut), 2):
  180. if cut[i] < 0:
  181. cut_send[i] = lens[i] + cut[i]
  182. cut_send[i+1] = abs(cut[i])-abs(cut[i+1])
  183. client_socket.sendall(json.dumps({"image_full":img,"image_sizes":{"x":65,"y":0,"width":125,"height":140},"load":data}).encode('gbk')+b"\n")
  184. img_counter += 1
  185. except:
  186. socket_switch = True
  187. if img_counter % 10 == 0:
  188. # get_temps()
  189. pass
  190. except Exception as e:
  191. if hasattr(e, 'message'):
  192. print(e.message)
  193. else:
  194. print(e)
  195. break
  196. if not socket_switch:
  197. client_socket.sendall(b"Bye\n")
  198. cam.release()
  199. cv2.destroyAllWindows()
  200. cam.release()
  201. kill = False
  202. thread.join()