baotrung217

test-multithreading

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