baotrung217

inference3

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