baotrung217

test-multithreading2

Apr 25th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.22 KB | None | 0 0
  1. from __future__ import print_function
  2.  
  3. import argparse
  4. import os
  5. import sys
  6. import time
  7. import tensorflow as tf
  8. import numpy as np
  9. from scipy import misc
  10. import cv2
  11. from matplotlib import pyplot as plt
  12.  
  13. from imutils.video import VideoStream
  14. from imutils.video import FPS
  15. from multiprocessing import Process
  16. from multiprocessing import Queue
  17. import imutils
  18.  
  19. from model import PSPNet101, PSPNet50
  20. from tools import *
  21.  
  22. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
  23.  
  24. ADE20k_param = {'crop_size': [473, 473],
  25. 'num_classes': 150,
  26. 'model': PSPNet50}
  27. cityscapes_param = {'crop_size': [720, 720],
  28. 'num_classes': 19,
  29. 'model': PSPNet101}
  30.  
  31. SAVE_DIR = './output/'
  32. SNAPSHOT_DIR = './model/'
  33. VIDEO_PATH = './input/085853AA.mp4'
  34.  
  35. def get_arguments():
  36. parser = argparse.ArgumentParser(description="Reproduced PSPNet")
  37. parser.add_argument("--img-path", type=str, default='',
  38. help="Path to the RGB image file.")
  39. parser.add_argument("--checkpoints", type=str, default=SNAPSHOT_DIR,
  40. help="Path to restore weights.")
  41. parser.add_argument("--save-dir", type=str, default=SAVE_DIR,
  42. help="Path to save output.")
  43. parser.add_argument("--flipped-eval", action="store_true",
  44. help="whether to evaluate with flipped img.")
  45. parser.add_argument("--dataset", type=str, default='cityscapes',
  46. choices=['ade20k', 'cityscapes'])
  47. parser.add_argument("--source", type=str, default='video',
  48. choices=['camera', 'video'])
  49.  
  50. return parser.parse_args()
  51.  
  52. def save(saver, sess, logdir, step):
  53. model_name = 'model.ckpt'
  54. checkpoint_path = os.path.join(logdir, model_name)
  55.  
  56. if not os.path.exists(logdir):
  57. os.makedirs(logdir)
  58. saver.save(sess, checkpoint_path, global_step=step)
  59. print('The checkpoint has been created.')
  60.  
  61. def load(saver, sess, ckpt_path):
  62. saver.restore(sess, ckpt_path)
  63. print("Restored model parameters from {}".format(ckpt_path))
  64.  
  65. def create_blank(height, width, rgb_color=(0, 0, 0)):
  66. """Create new image(numpy array) filled with certain color in RGB"""
  67. # Create black blank image
  68. image = np.zeros((height, width, 3), np.uint8)
  69.  
  70. # Since OpenCV uses BGR, convert the color first
  71. color = tuple(reversed(rgb_color))
  72. # Fill image with color
  73. image[:] = color
  74.  
  75. return image
  76.  
  77. def twoImgShowVertically(img1, img2, border):
  78. h, w, channels = img1.shape
  79.  
  80. img2 = cv2.resize(img2, (w, h))
  81. both = create_blank(h + border * 2, w * 2 + border * 3)
  82.  
  83. both[border:border + h, border:border + w] = img1.copy()
  84. both[border:border + h, border * 2 + w:border * 2 + w * 2] = img2.copy()
  85.  
  86. return both
  87.  
  88. def twoImgShowHorizontally(img1, img2, border):
  89. h, w, channels = img1.shape
  90.  
  91. img2 = cv2.resize(img2, (w, h))
  92. both = create_blank(h * 2 + border * 3, w + border * 2)
  93.  
  94. both[border:border + h, border:border + w] = img1.copy()
  95. both[border * 2 + h:border * 2 + h * 2, border:border + w] = img2.copy()
  96.  
  97. return both
  98.  
  99. def main():
  100. args = get_arguments()
  101.  
  102. ###########################################################
  103. # load parameters
  104. if args.dataset == 'ade20k':
  105. param = ADE20k_param
  106. elif args.dataset == 'cityscapes':
  107. param = cityscapes_param
  108.  
  109. crop_size = param['crop_size']
  110. num_classes = param['num_classes']
  111. PSPNet = param['model']
  112.  
  113. # preprocess images
  114. image_filename = tf.placeholder(dtype=tf.string)
  115. img = tf.image.decode_image(tf.read_file(image_filename), channels=3)
  116. img.set_shape([None, None, 3])
  117.  
  118. img_shape = tf.shape(img)
  119. h, w = (tf.maximum(crop_size[0], img_shape[0]), tf.maximum(crop_size[1], img_shape[1]))
  120. img = preprocess(img, h, w)
  121.  
  122. # Create network.
  123. print("[INFO] loading model...")
  124. net = PSPNet({'data': img}, is_training=False, num_classes=num_classes)
  125. with tf.variable_scope('', reuse=True):
  126. flipped_img = tf.image.flip_left_right(tf.squeeze(img))
  127. flipped_img = tf.expand_dims(flipped_img, dim=0)
  128. net2 = PSPNet({'data': flipped_img}, is_training=False, num_classes=num_classes)
  129.  
  130. raw_output = net.layers['conv6']
  131.  
  132. # Do flipped eval or not
  133. if args.flipped_eval:
  134. flipped_output = tf.image.flip_left_right(tf.squeeze(net2.layers['conv6']))
  135. flipped_output = tf.expand_dims(flipped_output, dim=0)
  136. raw_output = tf.add_n([raw_output, flipped_output])
  137.  
  138. # Predictions.
  139. raw_output_up = tf.image.resize_bilinear(raw_output, size=[h, w], align_corners=True)
  140. raw_output_up = tf.image.crop_to_bounding_box(raw_output_up, 0, 0, img_shape[0], img_shape[1])
  141. raw_output_up = tf.argmax(raw_output_up, axis=3)
  142. pred = decode_labels(raw_output_up, img_shape, num_classes)
  143.  
  144. # Init tf Session
  145. config = tf.ConfigProto()
  146. config.gpu_options.allow_growth = True
  147. sess = tf.Session(config=config)
  148. init = tf.global_variables_initializer()
  149.  
  150. sess.run(init)
  151.  
  152. restore_var = tf.global_variables()
  153. #print(restore_var)
  154. # Load checkpoint
  155. ckpt = tf.train.get_checkpoint_state(args.checkpoints)
  156. if ckpt and ckpt.model_checkpoint_path:
  157. loader = tf.train.Saver(var_list=restore_var)
  158. load_step = int(os.path.basename(ckpt.model_checkpoint_path).split('-')[1])
  159. load(loader, sess, ckpt.model_checkpoint_path)
  160. else:
  161. print('No checkpoint file found.')
  162.  
  163. def classify_frame(model, inputQueue, outputQueue):
  164. while True:
  165. if not inputQueue.empty():
  166. # grab the frame from the input queue, resize it, and
  167. # construct a blob from it
  168. input_name = inputQueue.get()
  169. print(input_name)
  170.  
  171. preds = sess.run(model, feed_dict={image_filename: input_name})
  172. prediction = preds[0]
  173.  
  174. # write the detections to the output queue
  175. outputQueue.put(prediction)
  176.  
  177. # initialize the input queue (detected faces grayed), output queue (predictions),
  178. inputQueue = Queue(maxsize=4)
  179. outputQueue = Queue(maxsize=4)
  180. out = None
  181. #cv2.imshow('abco', out)
  182.  
  183. # Capture the video source
  184. if args.source == 'camera':
  185. cap = cv2.VideoCapture(0)
  186. elif args.source == 'video':
  187. cap = cv2.VideoCapture(VIDEO_PATH)
  188.  
  189. # Check if camera opened successfully
  190. if (cap.isOpened() == False):
  191. print("Error opening video stream or file")
  192.  
  193. # initialize the prediction process
  194. p = Process(target=classify_frame, args=(pred, inputQueue, outputQueue,))
  195. p.daemon = True
  196. p.start()
  197.  
  198. fps = FPS().start()
  199.  
  200. # Read until video is completed
  201. while(cap.isOpened()):
  202. # Capture frame-by-frame
  203. ret, frame = cap.read()
  204. frameId = int(cap.get(1)) # current frame number
  205. frame = cv2.resize(frame, None, fx=1/6, fy=1/6)
  206.  
  207. name = './tmp/' + str(frameId) + '.jpg'
  208. cv2.imwrite(name, frame)
  209.  
  210. if ret == True:
  211.  
  212. # if the input queue *is* empty, give the current frame to
  213. # classify
  214. if inputQueue.empty():
  215. inputQueue.put(name)
  216.  
  217. # if the output queue *is not* empty, grab the detections
  218. if not outputQueue.empty():
  219. out = outputQueue.get()
  220. #else:
  221. # print('outputQueue is empty')
  222.  
  223. cv2.imshow('Original', frame)
  224. cv2.imshow('Result', out)
  225. # Press ESC on keyboard to exit
  226. if cv2.waitKey(33) & 0xFF == ord('q'):
  227. break
  228.  
  229. # update the FPS counter
  230. fps.update()
  231.  
  232. else:
  233. break
  234.  
  235. os.remove(name)
  236.  
  237. # stop the timer and display FPS information
  238. fps.stop()
  239. print("[INFO] elapsed time: {:.2f}".format(fps.elapsed()))
  240. print("[INFO] approx. FPS: {:.2f}".format(fps.fps()))
  241.  
  242. # When everything done, release the video capture object
  243. cap.release()
  244.  
  245. sess.close()
  246.  
  247. # Closes all the frames
  248. cv2.destroyAllWindows()
  249.  
  250.  
  251. if __name__ == '__main__':
  252. main()
Advertisement
Add Comment
Please, Sign In to add comment