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.

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