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.

154 lines
6.2 KiB

6 years ago
  1. #!/usr/bin/python3
  2. import numpy as np
  3. import os
  4. import six.moves.urllib as urllib
  5. import sys
  6. import tarfile
  7. import tensorflow as tf
  8. import zipfile
  9. import cv2
  10. from distutils.version import StrictVersion
  11. from collections import defaultdict
  12. from io import StringIO
  13. from utils import label_map_util
  14. from utils import visualization_utils as vis_util
  15. from PIL import Image
  16. switch = 1
  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. #MODEL_NAME = 'ssd_mobilenet_v1_coco_2017_11_17' #not even worth trying
  25. MODEL_NAME="ssd_inception_v2_coco_11_06_2017" # not bad and fast
  26. MODEL_NAME="rfcn_resnet101_coco_11_06_2017" # WORKS BEST BUT takes 4 times longer per image
  27. #MODEL_NAME = "faster_rcnn_resnet101_coco_11_06_2017" # too slow
  28. MODEL_FILE = MODEL_NAME + '.tar.gz'
  29. DOWNLOAD_BASE = 'http://download.tensorflow.org/models/object_detection/'
  30. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  31. PATH_TO_FROZEN_GRAPH = MODEL_NAME + '/frozen_inference_graph.pb'
  32. # List of the strings that is used to add correct label for each box.
  33. PATH_TO_LABELS = os.path.join('object_detection/data', 'mscoco_label_map.pbtxt')
  34. detection_graph = tf.Graph()
  35. with detection_graph.as_default():
  36. od_graph_def = tf.GraphDef()
  37. with tf.gfile.GFile(PATH_TO_FROZEN_GRAPH, 'rb') as fid:
  38. serialized_graph = fid.read()
  39. od_graph_def.ParseFromString(serialized_graph)
  40. tf.import_graph_def(od_graph_def, name='')
  41. category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
  42. def load_image_into_numpy_array(image):
  43. (im_width, im_height) = image.size
  44. return np.array(image.getdata()).reshape(
  45. (im_height, im_width, 3)).astype(np.uint8)
  46. # For the sake of simplicity we will use only 2 images:
  47. # image1.jpg
  48. # image2.jpg
  49. # If you want to test the code with your images, just add path to the images to the TEST_IMAGE_PATHS.
  50. PATH_TO_TEST_IMAGES_DIR = 'object_detection/test_images'
  51. TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(3, 6) ]
  52. # Size, in inches, of the output images.
  53. sess = 0
  54. switch = 1
  55. def run_inference_for_single_image(image, graph):
  56. global switch
  57. global sess
  58. with graph.as_default():
  59. if(switch):
  60. sess = tf.Session()
  61. switch = 0
  62. # Get handles to input and output tensors
  63. ops = tf.get_default_graph().get_operations()
  64. all_tensor_names = {output.name for op in ops for output in op.outputs}
  65. tensor_dict = {}
  66. for key in [
  67. 'num_detections', 'detection_boxes', 'detection_scores',
  68. 'detection_classes', 'detection_masks'
  69. ]:
  70. tensor_name = key + ':0'
  71. if tensor_name in all_tensor_names:
  72. tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
  73. tensor_name)
  74. if 'detection_masks' in tensor_dict:
  75. # The following processing is only for single image
  76. detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
  77. detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
  78. # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
  79. real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
  80. detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
  81. detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
  82. detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
  83. detection_masks, detection_boxes, image.shape[1], image.shape[2])
  84. detection_masks_reframed = tf.cast(
  85. tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  86. # Follow the convention by adding back the batch dimension
  87. tensor_dict['detection_masks'] = tf.expand_dims(
  88. detection_masks_reframed, 0)
  89. image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
  90. # Run inference
  91. output_dict = sess.run(tensor_dict,
  92. feed_dict={image_tensor: image})
  93. # all outputs are float32 numpy arrays, so convert types as appropriate
  94. output_dict['num_detections'] = int(output_dict['num_detections'][0])
  95. output_dict['detection_classes'] = output_dict[
  96. 'detection_classes'][0].astype(np.int64)
  97. output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  98. output_dict['detection_scores'] = output_dict['detection_scores'][0]
  99. if 'detection_masks' in output_dict:
  100. output_dict['detection_masks'] = output_dict['detection_masks'][0]
  101. return output_dict
  102. cut=[-175,-1,-175,-1]
  103. a = 1
  104. cam = cv2.VideoCapture(0)
  105. with detection_graph.as_default():
  106. sess = tf.Session()
  107. switch = 0
  108. while 1:
  109. if(True):
  110. ret,image = cam.read()
  111. image_np = image[cut[0]:cut[1],cut[2]:cut[3]]
  112. #image_np = image_np[int(r[1]):int(r[1]+r[3]),int(r[0]):int(r[0]+r[2])]
  113. # the array based representation of the image will be used later in order to prepare the
  114. # result image with boxes and labels on it.
  115. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  116. image_np_expanded = np.expand_dims(image_np, axis=0)
  117. t1 = time.time()
  118. # Actual detection.
  119. output_dict = run_inference_for_single_image(image_np_expanded, detection_graph)
  120. # Visualization of the results of a detection.
  121. vis_util.visualize_boxes_and_labels_on_image_array(
  122. image_np,
  123. output_dict['detection_boxes'],
  124. output_dict['detection_classes'],
  125. output_dict['detection_scores'],
  126. category_index,
  127. instance_masks=output_dict.get('detection_masks'),
  128. use_normalized_coordinates=True,
  129. line_thickness=8)
  130. image[cut[0]:cut[1],cut[2]:cut[3]] = image_np
  131. cv2.imshow("Cam",np.concatenate((image,image_np),axis=0))
  132. t2 = time.time()
  133. print("time taken for {}".format(t2-t1))
  134. ex_c = [27, ord("q"), ord("Q")]
  135. if cv2.waitKey(1) & 0xFF in ex_c:
  136. break
  137. cv2.destroyAllWindows()
  138. cam.release()