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.

181 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 numpy as np
  3. import os
  4. import sys
  5. import tensorflow as tf
  6. import cv2
  7. from distutils.version import StrictVersion
  8. from utils import label_map_util
  9. from utils import visualization_utils as vis_util
  10. switch = 1
  11. import io
  12. import socket
  13. import struct
  14. import time
  15. import pickle
  16. import zlib
  17. # This is needed since the notebook is stored in the object_detection folder.
  18. sys.path.append("..")
  19. import time
  20. from object_detection.utils import ops as utils_ops
  21. if StrictVersion(tf.__version__) < StrictVersion('1.12.0'):
  22. raise ImportError('Please upgrade your TensorFlow installation to v1.12.*.')
  23. # What model to download.
  24. encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 90]
  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. def run_inference_for_single_image(image, graph):
  57. global switch
  58. global sess
  59. with graph.as_default():
  60. if(switch):
  61. sess = tf.Session()
  62. switch = 0
  63. # Get handles to input and output tensors
  64. ops = tf.get_default_graph().get_operations()
  65. all_tensor_names = {output.name for op in ops for output in op.outputs}
  66. tensor_dict = {}
  67. for key in [
  68. 'num_detections', 'detection_boxes', 'detection_scores',
  69. 'detection_classes', 'detection_masks'
  70. ]:
  71. tensor_name = key + ':0'
  72. if tensor_name in all_tensor_names:
  73. tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
  74. tensor_name)
  75. if 'detection_masks' in tensor_dict:
  76. # The following processing is only for single image
  77. detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
  78. detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
  79. # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
  80. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
  81. detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
  82. detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
  83. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
  84. detection_masks, detection_boxes, image.shape[1], image.shape[2])
  85. detection_masks_reframed = tf.cast(
  86. tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  87. # Follow the convention by adding back the batch dimension
  88. tensor_dict['detection_masks'] = tf.expand_dims(
  89. detection_masks_reframed, 0)
  90. image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
  91. # Run inference
  92. output_dict = sess.run(tensor_dict,
  93. feed_dict={image_tensor: image})
  94. # all outputs are float32 numpy arrays, so convert types as appropriate
  95. output_dict['num_detections'] = int(output_dict['num_detections'][0])
  96. output_dict['detection_classes'] = output_dict[
  97. 'detection_classes'][0].astype(np.int64)
  98. output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  99. output_dict['detection_scores'] = output_dict['detection_scores'][0]
  100. if 'detection_masks' in output_dict:
  101. output_dict['detection_masks'] = output_dict['detection_masks'][0]
  102. return output_dict
  103. cut=[-225,-1,-225,-1]
  104. a = 1
  105. cam = cv2.VideoCapture(1)
  106. conn_switch = False
  107. with detection_graph.as_default():
  108. sess = tf.Session()
  109. switch = 0
  110. while 1:
  111. if(True):
  112. ret,image = cam.read()
  113. image_np = image[cut[0]:cut[1],cut[2]:cut[3]]
  114. #image_np = image_np[int(r[1]):int(r[1]+r[3]),int(r[0]):int(r[0]+r[2])]
  115. # the array based representation of the image will be used later in order to prepare the
  116. # result image with boxes and labels on it.
  117. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  118. image_np_expanded = np.expand_dims(image_np, axis=0)
  119. t1 = time.time()
  120. # Actual detection.
  121. output_dict = run_inference_for_single_image(image_np_expanded, detection_graph)
  122. # Visualization of the results of a detection.
  123. vis_util.visualize_boxes_and_labels_on_image_array(
  124. image_np,
  125. output_dict['detection_boxes'],
  126. output_dict['detection_classes'],
  127. output_dict['detection_scores'],
  128. category_index,
  129. instance_masks=output_dict.get('detection_masks'),
  130. use_normalized_coordinates=True,
  131. line_thickness=8,
  132. min_score_thresh=0.4)
  133. image[cut[0]:cut[1],cut[2]:cut[3]] = image_np
  134. result, frame = cv2.imencode('.jpg', image, encode_param)
  135. data = pickle.dumps(frame, 0)
  136. size = len(data)
  137. if(conn_switch):
  138. pass
  139. else:
  140. try:
  141. client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  142. client_socket.connect(('10.10.26.115', 8488))
  143. connection = client_socket.makefile('wb')
  144. conn_switch = True
  145. except:
  146. pass
  147. try:
  148. client_socket.sendall(struct.pack(">L", size) + data)
  149. except:
  150. conn_switch = False
  151. cv2.imshow("Cam",image)
  152. cv2.imshow("Cut",image_np)
  153. t2 = time.time()
  154. print("time taken for {}".format(t2-t1))
  155. ex_c = [27, ord("q"), ord("Q")]
  156. if cv2.waitKey(1) & 0xFF in ex_c:
  157. break
  158. cv2.destroyAllWindows()
  159. cam.release()