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.

203 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
  1. #!/usr/bin/python3
  2. import numpy as np
  3. import os
  4. import sys
  5. import tensorflow as tf
  6. import cv2
  7. from distutils.version import StrictVersion
  8. import socket
  9. from utils import label_map_util
  10. from utils import visualization_utils as vis_util
  11. import psutil
  12. import json
  13. import base64
  14. from PIL import Image
  15. from io import BytesIO
  16. import psutil
  17. switch = 1
  18. # This is needed since the notebook is stored in the object_detection folder.
  19. sys.path.append("..")
  20. import time
  21. from object_detection.utils import ops as utils_ops
  22. if StrictVersion(tf.__version__) < StrictVersion('1.12.0'):
  23. raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')
  24. # What model to download.
  25. #MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17' #not even worth trying
  26. MODEL_NAME="ssd_inception_v2_coco_11_06_2017" # not bad and fast
  27. MODEL_NAME="rfcn_resnet101_coco_11_06_2017" # WORKS BEST BUT takes 4 times longer per image
  28. #MODEL_NAME = "faster_rcnn_resnet101_coco_11_06_2017" # too slow
  29. MODEL_FILE = MODEL_NAME + '.tar.gz'
  30. DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
  31. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  32. PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
  33. # List of the strings that is used to add correct label for each box.
  34. PATH_TO_LABELS = os.path.join('object_detection/data', 'mscoco_label_map.pbtxt')
  35. detection_graph = tf.Graph()
  36. with detection_graph.as_default():
  37. od_graph_def = tf.GraphDef()
  38. with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
  39. serialized_graph = fid.read()
  40. od_graph_def.ParseFromString(serialized_graph)
  41. tf.import_graph_def(od_graph_def, name='')
  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. # For the sake of simplicity we will use only 2 images:
  48. # image1.jpg
  49. # image2.jpg
  50. # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
  51. PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images'
  52. TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(3, 6) ]
  53. # Size, in inches, of the output images.
  54. sess = 0
  55. switch = 1
  56. data = {"gpu_temp":"10C","gpu_load":"15%","cpu_temp":"47C","cpu_load":"15%","mem_temp":"NaN","mem_load":"17%","fan_speed":"10000RPM"}
  57. def get_temps():
  58. global data
  59. temps = psutil.sensors_temperatures()
  60. data["cpu_temp"] = str(int(temps["dell_smm"][0][1]))+"°C"
  61. data["cpu_load"] = str(psutil.cpu_percent())+"%"
  62. data["mem_load"] = str(dict(psutil.virtual_memory()._asdict())["percent"])+"%"
  63. data["fan_speed"] = str(psutil.sensors_fans()["dell_smm"][0][1])+"RPM"
  64. def run_inference_for_single_image(image, graph):
  65. global switch
  66. global sess
  67. with graph.as_default():
  68. if(switch):
  69. sess = tf.Session()
  70. switch = 0
  71. # Get handles to input and output tensors
  72. ops = tf.get_default_graph().get_operations()
  73. all_tensor_names = {output.name for op in ops for output in op.outputs}
  74. tensor_dict = {}
  75. for key in [
  76. 'num_detections', 'detection_boxes', 'detection_scores',
  77. 'detection_classes', 'detection_masks'
  78. ]:
  79. tensor_name = key + ':0'
  80. if tensor_name in all_tensor_names:
  81. tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
  82. tensor_name)
  83. if 'detection_masks' in tensor_dict:
  84. # The following processing is only for single image
  85. detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
  86. detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
  87. # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
  88. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
  89. detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
  90. detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
  91. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
  92. detection_masks, detection_boxes, image.shape[1], image.shape[2])
  93. detection_masks_reframed = tf.cast(
  94. tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  95. # Follow the convention by adding back the batch dimension
  96. tensor_dict['detection_masks'] = tf.expand_dims(
  97. detection_masks_reframed, 0)
  98. image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
  99. # Run inference
  100. output_dict = sess.run(tensor_dict,
  101. feed_dict={image_tensor: image})
  102. # all outputs are float32 numpy arrays, so convert types as appropriate
  103. output_dict['num_detections'] = int(output_dict['num_detections'][0])
  104. output_dict['detection_classes'] = output_dict[
  105. 'detection_classes'][0].astype(np.int64)
  106. output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  107. output_dict['detection_scores'] = output_dict['detection_scores'][0]
  108. if 'detection_masks' in output_dict:
  109. output_dict['detection_masks'] = output_dict['detection_masks'][0]
  110. return output_dict
  111. cut=[-175,-1,-175,-1]
  112. cut_send = [0,0,0,0]
  113. a = 1
  114. img_counter = 0
  115. socket_switch = True
  116. cam = cv2.VideoCapture(0)
  117. with detection_graph.as_default():
  118. sess = tf.Session()
  119. switch = 0
  120. get_temps()
  121. while 1:
  122. if(True):
  123. try:
  124. ret,image = cam.read()
  125. image_np = image[cut[0]:cut[1],cut[2]:cut[3]]
  126. #image_np = image_np[int(r[1]):int(r[1]+r[3]),int(r[0]):int(r[0]+r[2])]
  127. # the array based representation of the image will be used later in order to prepare the
  128. # result image with boxes and labels on it.
  129. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  130. image_np_expanded = np.expand_dims(image_np, axis=0)
  131. t1 = time.time()
  132. # Actual detection.
  133. output_dict = run_inference_for_single_image(image_np_expanded, detection_graph)
  134. # Visualization of the results of a detection.
  135. vis_util.visualize_boxes_and_labels_on_image_array(
  136. image_np,
  137. output_dict['detection_boxes'],
  138. output_dict['detection_classes'],
  139. output_dict['detection_scores'],
  140. category_index,
  141. instance_masks=output_dict.get('detection_masks'),
  142. use_normalized_coordinates=True,
  143. line_thickness=8)
  144. image[cut[0]:cut[1],cut[2]:cut[3]] = image_np
  145. send_image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
  146. cv2.imshow("Cam",image)
  147. cv2.imshow("Cut",image_np)
  148. if socket_switch:
  149. try:
  150. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  151. client_socket.connect(('127.0.0.1', 8485))
  152. connection = client_socket.makefile('wb')
  153. socket_switch = False
  154. except:
  155. socket_switch=True
  156. continue
  157. try:
  158. crop_img = send_image.copy(order='C')
  159. crop_img = Image.fromarray(crop_img,"RGB")
  160. buffered = BytesIO()
  161. crop_img.save(buffered, format="JPEG")
  162. img = base64.b64encode(buffered.getvalue()).decode("ascii")
  163. 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")
  164. img_counter += 1
  165. except:
  166. socket_switch=True
  167. if img_counter % 10 ==0:
  168. get_temps()
  169. t2 = time.time()
  170. print("time taken for {}".format(t2-t1))
  171. ex_c = [27, ord("q"), ord("Q")]
  172. if cv2.waitKey(1) & 0xFF in ex_c:
  173. break
  174. except KeyboardInterrupt:
  175. if not socket_switch:
  176. client_socket.sendall(b"Bye\n")
  177. cam.release()
  178. exit(0)
  179. cv2.destroyAllWindows()
  180. cam.release()