baotrung217

inference1

Mar 14th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.48 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 model import PSPNet101, PSPNet50
  14. from tools import *
  15.  
  16. ADE20k_param = {'crop_size': [473, 473],
  17.                 'num_classes': 150,
  18.                 'model': PSPNet50}
  19. cityscapes_param = {'crop_size': [720, 720],
  20.                     'num_classes': 19,
  21.                     'model': PSPNet101}
  22.  
  23. SAVE_DIR = './output/'
  24. SNAPSHOT_DIR = './model/tmp/'
  25. VIDEO_PATH = './input/video_2.mp4'
  26. CAPTURE_FROM_CAMERA = False
  27.  
  28. def get_arguments():
  29.     parser = argparse.ArgumentParser(description="Reproduced PSPNet")
  30.     parser.add_argument("--img-path", type=str, default='',
  31.                         help="Path to the RGB image file.")
  32.     parser.add_argument("--checkpoints", type=str, default=SNAPSHOT_DIR,
  33.                         help="Path to restore weights.")
  34.     parser.add_argument("--save-dir", type=str, default=SAVE_DIR,
  35.                         help="Path to save output.")
  36.     parser.add_argument("--flipped-eval", action="store_true",
  37.                         help="whether to evaluate with flipped img.")
  38.     parser.add_argument("--dataset", type=str, default='cityscapes',
  39.                         choices=['ade20k', 'cityscapes'])
  40.  
  41.     return parser.parse_args()
  42.  
  43. def save(saver, sess, logdir, step):
  44.    model_name = 'model.ckpt'
  45.    checkpoint_path = os.path.join(logdir, model_name)
  46.  
  47.    if not os.path.exists(logdir):
  48.       os.makedirs(logdir)
  49.    saver.save(sess, checkpoint_path, global_step=step)
  50.    print('The checkpoint has been created.')
  51.  
  52. def load(saver, sess, ckpt_path):
  53.     saver.restore(sess, ckpt_path)
  54.     print("Restored model parameters from {}".format(ckpt_path))
  55.  
  56. def create_blank(height, width, rgb_color=(0, 0, 0)):
  57.     """Create new image(numpy array) filled with certain color in RGB"""
  58.     # Create black blank image
  59.     image = np.zeros((height, width, 3), np.uint8)
  60.  
  61.     # Since OpenCV uses BGR, convert the color first
  62.     color = tuple(reversed(rgb_color))
  63.     # Fill image with color
  64.     image[:] = color
  65.  
  66.     return image
  67.  
  68. def twoImgShowVertically(img1, img2, border):
  69.     h, w, channels = img1.shape
  70.  
  71.     img2 = cv2.resize(img2, (w, h))
  72.     both = create_blank(h + border * 2, w * 2 + border * 3)
  73.  
  74.     both[border:border + h, border:border + w] = img1.copy()
  75.     both[border:border + h, border * 2 + w:border * 2 + w * 2] = img2.copy()
  76.  
  77.     return both
  78.  
  79. def twoImgShowHorizontally(img1, img2, border):
  80.     h, w, channels = img1.shape
  81.  
  82.     img2 = cv2.resize(img2, (w, h))
  83.     both = create_blank(h * 2 + border * 3, w + border * 2)
  84.  
  85.     both[border:border + h, border:border + w] = img1.copy()
  86.     both[border * 2 + h:border * 2 + h * 2, border:border + w] = img2.copy()
  87.  
  88.     return both
  89.  
  90. def main():
  91.     args = get_arguments()
  92.  
  93.     ############################################################
  94.     # load parameters
  95.     if args.dataset == 'ade20k':
  96.         param = ADE20k_param
  97.     elif args.dataset == 'cityscapes':
  98.         param = cityscapes_param
  99.  
  100.     crop_size = param['crop_size']
  101.     num_classes = param['num_classes']
  102.     PSPNet = param['model']
  103.  
  104.     if CAPTURE_FROM_CAMERA:
  105.         cap = cv2.VideoCapture(0)
  106.     else:
  107.         cap = cv2.VideoCapture(VIDEO_PATH)
  108.  
  109.     # Check if camera opened successfully
  110.     if (cap.isOpened()== False):
  111.         print("Error opening video stream or file")
  112.  
  113.     # Read until video is completed
  114.     while(cap.isOpened()):
  115.         # Capture frame-by-frame
  116.         ret, frame = cap.read()
  117.    
  118.         if ret == True:
  119.             frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)
  120.            
  121.             # Display the resulting frame
  122.             result = twoImgShowHorizontally(frame, frame, 50)
  123.             cv2.imshow('Video 2', result)
  124.             # Press ESC on keyboard to  exit
  125.             if cv2.waitKey(25) & 0xFF == ord('q'):
  126.                 break
  127.          
  128.             # elif cv2.waitKey(25) & 0xFF == ord('c'):
  129.             #     cap = cv2.VideoCapture(0)
  130.             # elif cv2.waitKey(25) & 0xFF == ord('v'):
  131.             #     cap = cv2.VideoCapture(VIDEO_PATH)
  132.         else:
  133.             break
  134.  
  135.     # When everything done, release the video capture object
  136.     cap.release()
  137.  
  138.     # Closes all the frames
  139.     cv2.destroyAllWindows()
  140.     ###########################################################
  141.  
  142.     '''
  143.    # preprocess images
  144.    img, filename = load_img(args.img_path)
  145.    img_shape = tf.shape(img)
  146.    h, w = (tf.maximum(crop_size[0], img_shape[0]), tf.maximum(crop_size[1], img_shape[1]))
  147.    img = preprocess(img, h, w)
  148.  
  149.    # Create network.
  150.    net = PSPNet({'data': img}, is_training=False, num_classes=num_classes)
  151.    with tf.variable_scope('', reuse=True):
  152.        flipped_img = tf.image.flip_left_right(tf.squeeze(img))
  153.        flipped_img = tf.expand_dims(flipped_img, dim=0)
  154.        net2 = PSPNet({'data': flipped_img}, is_training=False, num_classes=num_classes)
  155.  
  156.    raw_output = net.layers['conv6']
  157.    
  158.    # Do flipped eval or not
  159.    if args.flipped_eval:
  160.        flipped_output = tf.image.flip_left_right(tf.squeeze(net2.layers['conv6']))
  161.        flipped_output = tf.expand_dims(flipped_output, dim=0)
  162.        raw_output = tf.add_n([raw_output, flipped_output])
  163.  
  164.    # Predictions.
  165.    raw_output_up = tf.image.resize_bilinear(raw_output, size=[h, w], align_corners=True)
  166.    raw_output_up = tf.image.crop_to_bounding_box(raw_output_up, 0, 0, img_shape[0], img_shape[1])
  167.    raw_output_up = tf.argmax(raw_output_up, axis=3)
  168.    pred = decode_labels(raw_output_up, img_shape, num_classes)
  169.    
  170.    # Init tf Session
  171.    config = tf.ConfigProto()
  172.    config.gpu_options.allow_growth = True
  173.    sess = tf.Session(config=config)
  174.    init = tf.global_variables_initializer()
  175.  
  176.    sess.run(init)
  177.    
  178.    restore_var = tf.global_variables()
  179.    
  180.    ckpt = tf.train.get_checkpoint_state(args.checkpoints)
  181.    if ckpt and ckpt.model_checkpoint_path:
  182.        loader = tf.train.Saver(var_list=restore_var)
  183.        load_step = int(os.path.basename(ckpt.model_checkpoint_path).split('-')[1])
  184.        load(loader, sess, ckpt.model_checkpoint_path)
  185.    else:
  186.        print('No checkpoint file found.')
  187.    
  188.    preds = sess.run(pred)
  189.    
  190.    if not os.path.exists(args.save_dir):
  191.        os.makedirs(args.save_dir)
  192.    misc.imsave(args.save_dir + filename, preds[0])
  193.    '''
  194.    
  195. if __name__ == '__main__':
  196.     main()
Advertisement
Add Comment
Please, Sign In to add comment