Advertisement
Guest User

Untitled

a guest
Nov 29th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.73 KB | None | 0 0
  1. ######## Object Detection for Image #########
  2. #
  3. # Author: Khai Do
  4. # Date: 9/3/2019
  5.  
  6. ## Some parts of the code is copied from Tensorflow object detection
  7. ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb
  8.  
  9.  
  10. # Import libraries
  11. from pandas._libs import json
  12. import numpy as np
  13. import os
  14. import six.moves.urllib as urllib
  15. import sys
  16. import tarfile
  17. import tensorflow as tf
  18. import zipfile
  19. import cv2
  20.  
  21. from collections import defaultdict
  22. from io import StringIO
  23. from matplotlib import pyplot as plt
  24. from PIL import Image
  25. from models.research.object_detection.utils import label_map_util
  26. from models.research.object_detection.utils import visualization_utils as vis_util
  27.  
  28. # Define the video stream
  29. cap = cv2.VideoCapture(0) # Change only if you have more than one webcams
  30.  
  31. # What model
  32. directPath = os.getcwd()
  33. print(directPath)
  34. MODEL_NAME = os.path.join(directPath, 'trained-inference-graphs/output_inference_graph_v1.pb')
  35.  
  36. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  37. PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
  38.  
  39. # List of the strings that is used to add correct label for each box.
  40. PATH_TO_LABELS = os.path.join(directPath, 'training/label_map.pbtxt')
  41.  
  42. # Number of classes to detect
  43. NUM_CLASSES = 3
  44.  
  45.  
  46. # Load a (frozen) Tensorflow model into memory.
  47. detection_graph = tf.Graph()
  48. with detection_graph.as_default():
  49. od_graph_def = tf.GraphDef()
  50. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  51. serialized_graph = fid.read()
  52. od_graph_def.ParseFromString(serialized_graph)
  53. tf.import_graph_def(od_graph_def, name='')
  54.  
  55.  
  56. # Loading label map
  57. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  58. categories = label_map_util.convert_label_map_to_categories(
  59. label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
  60. category_index = label_map_util.create_category_index(categories)
  61.  
  62.  
  63. # Helper code
  64. def load_image_into_numpy_array(image):
  65. (im_width, im_height) = image.size
  66. return np.array(image.getdata()).reshape(
  67. (im_height, im_width, 3)).astype(np.uint8)
  68.  
  69.  
  70. # Detection
  71. with detection_graph.as_default():
  72. with tf.Session(graph=detection_graph) as sess:
  73. while True:
  74.  
  75. # Read frame from camera
  76. ret, image_np = cap.read()
  77. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  78. image_np_expanded = np.expand_dims(image_np, axis=0)
  79. # Extract image tensor
  80. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  81. # Extract detection boxes
  82. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  83. # Extract detection scores
  84. scores = detection_graph.get_tensor_by_name('detection_scores:0')
  85. # Extract detection classes
  86. classes = detection_graph.get_tensor_by_name('detection_classes:0')
  87. # Extract number of detectionsd
  88. num_detections = detection_graph.get_tensor_by_name(
  89. 'num_detections:0')
  90. # Actual detection.
  91. (boxes, scores, classes, num_detections) = sess.run(
  92. [boxes, scores, classes, num_detections],
  93. feed_dict={image_tensor: image_np_expanded})
  94. # Visualization of the results of a detection.
  95. vis_util.visualize_boxes_and_labels_on_image_array(
  96. image_np,
  97. np.squeeze(boxes),
  98. np.squeeze(classes).astype(np.int32),
  99. np.squeeze(scores),
  100. category_index,
  101. use_normalized_coordinates=True,
  102. line_thickness=8)
  103.  
  104. # writing coordinates
  105. coordinates = vis_util.return_coordinates(
  106. image_np,
  107. np.squeeze(boxes),
  108. np.squeeze(classes).astype(np.int32),
  109. np.squeeze(scores),
  110. category_index,
  111. use_normalized_coordinates=True,
  112. line_thickness=8,
  113. min_score_thresh=0.80)
  114.  
  115. for coordinate in coordinates:
  116. if not coordinate:
  117. print("Looking for guesture")
  118. else:
  119. print(coordinate)
  120. (y1, y2, x1, x2, scores, classes) = coordinate
  121.  
  122. #textfile = open('filename_string' + ".json", "a")
  123. #textfile.write(json.dumps(coordinate))
  124. #textfile.write("\n")
  125. #print(coordinates)
  126.  
  127. # Display output
  128. cv2.imshow('object detection', cv2.resize(image_np, (1200,900)))
  129.  
  130. if cv2.waitKey(25) & 0xFF == ord('q'):
  131. cv2.destroyAllWindows()
  132. break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement