text: from __future__ import print_function
  import os
  import numpy as np
  import tensorflow as tf
  
  import configparser
  import argparse
  import signal
  import glob
  
  os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
  import progressbar
  import cv2
  import utils as u
  from network import build_encoder
  #This is to generate the codebook \bar_C for inference, to run it: python single2_embed.py <experiment_name> <obj_id> <num_iterations>
  #e.g.: python single2_embed.py subdiv_29_softmax_edge 29 30000
  
  #Prerequisite before generating the codebook:
  #ckpt: under workspace_path/experiments/<experiment_name>/checkpoints_lambda250/checkpoints/ckpt-<num_iterations>-1
  #cfg file: <experiment_name>.cfg under the path: workspace_path/experiments/<experiment_name>/<experiment_name>.cfg
  #Rendered imgs and edgemaps under reference rotations \bar_R(Generated by render_codebook.py) under the path: path_embedding_data
  
  workspace_path = './ws/'
  if workspace_path == None:
      print('Please define a workspace path:\n')
      exit(-1)
  
  gentle_stop = np.array((1,), dtype=np.bool)
  gentle_stop[0] = False
  
  def on_ctrl_c(signal, frame):
      gentle_stop[0] = True
  signal.signal(signal.SIGINT, on_ctrl_c)
  
  parser = argparse.ArgumentParser()
  parser.add_argument("experiment_name")
  parser.add_argument("obj_id")
  parser.add_argument("num_iterations")
  
  
  arguments = parser.parse_args()
  
  full_name = arguments.experiment_name.split('/')
  obj_id=int(arguments.obj_id)
  num_iterations=int(arguments.num_iterations)
  
  experiment_name = full_name.pop()
  experiment_group = full_name.pop() if len(full_name) > 0 else ''
  
  log_dir = u.get_log_dir(workspace_path, experiment_name, experiment_group)
  ckpt_dir = os.path.join(log_dir, 'checkpoints_lambda250')
  checkpoint_file = u.get_checkpoint_basefilename(ckpt_dir)
  print('log_dir',log_dir)
  args = configparser.ConfigParser()
  cfg_file_path=glob.glob(os.path.join(log_dir,'*.cfg'))[0]
  args.read(cfg_file_path)
  
  tf.reset_default_graph()
  
  embedding_dim = 128
  image_size=128
  ci=4
  path_embedding_data = './embedding92232s/{:02d}'.format(obj_id) #path to dir of info \bar_R
  embedding_size = 92232
  normalize_images=True # Default false for non-textured TLESS CAD mesh, and True for texture meshes such as Linemod
  
  # Build modules.
  with tf.variable_scope(experiment_name):
      #################Normalize images###########################
      bgr_y=tf.placeholder(tf.uint8, shape=(image_size, image_size, 3))
      _normalized_bgr_y= tf.reshape(tf.image.per_image_standardization(bgr_y),[image_size,image_size,3])
      min_normalized_bgry=tf.reduce_min(_normalized_bgr_y)
      max_normalized_bgry=tf.reduce_max(_normalized_bgr_y)
      normalized_bgr_y=(_normalized_bgr_y-min_normalized_bgry)/(max_normalized_bgry-min_normalized_bgry)
      ############################################################
  
      x = tf.placeholder(tf.float32, shape=(None, image_size, image_size, ci))
      print('xshape', x.shape)
      with tf.variable_scope('encoder'):
          encoder = build_encoder(args)
      z=encoder(x)
      print('zshape: ', z.shape)
      network_vars = tf.trainable_variables()
      total_loss=0.
  
  def run_embedding(sess,dir_embedding,embedding_size):
      J = embedding_dim
      embedding_z = np.empty((embedding_size, J))
  
      widgets = ['Creating embedding ..: ', progressbar.Percentage(),
                 ' ', progressbar.Bar(),
                 ' ', progressbar.Counter(), ' / %s' % embedding_size,
                 ' ', progressbar.ETA(), ' ']
  
      bar = progressbar.ProgressBar(maxval=embedding_size, widgets=widgets)
      bar.start()
      mpath_embedding_imgs = os.path.join(dir_embedding, 'imgs', '{:05d}.png')  ###############
      mpath_embedding_inedges = os.path.join(dir_embedding, 'in_edges2', '{:05d}.png')  ###############
      mpath_embedding_out_imgs = os.path.join(dir_embedding, 'out_imgs')
      if not os.path.exists(os.path.join(dir_embedding, 'out_imgs')):
          os.makedirs(os.path.join(dir_embedding, 'out_imgs'))
  
      for i in range(0, embedding_size):
          bar.update(i)
          bgr_input = cv2.imread(mpath_embedding_imgs.format(i)).astype(np.uint8)
          bgr_input = cv2.resize(bgr_input, (image_size, image_size), interpolation=cv2.INTER_NEAREST)
          if normalize_images:
              normalized_bgr_input=sess.run(normalized_bgr_y,feed_dict={bgr_y:bgr_input})
              bgr_input=(normalized_bgr_input.copy()*255.).astype(np.uint8)
              edge_input=(cv2.Canny(bgr_input, 50, 150)[:, :, np.newaxis]).astype(np.uint8)
          else:
              edge_input = (cv2.imread(mpath_embedding_inedges.format(i), cv2.IMREAD_GRAYSCALE)[:, :, np.newaxis]).astype(np.uint8)
  
          if ci == 1:
              img_input = edge_input
          elif ci == 3:
              img_input = bgr_input
          else:
              img_input = np.concatenate((bgr_input, edge_input), axis=-1)
  
          if img_input.dtype == 'uint8':
              img_input = (img_input / 255.0)
          batch_input = img_input[np.newaxis, :].astype(np.float32)
          embedding_z[i, :] = sess.run(z, feed_dict={x: batch_input})[0, :]
      bar.finish()
  
      normalized_embedding = embedding_z/ np.linalg.norm(embedding_z, axis=1, keepdims=True)
      return normalized_embedding
  
  gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.9)
  config = tf.ConfigProto(gpu_options=gpu_options)
  with tf.Session(config=config) as sess:
      num_ites = num_iterations - 1
      tf.train.Saver(network_vars).restore(sess, os.path.join(ckpt_dir, 'checkpoints/chkpt-{0}'.format(num_ites)))
      print('Restore checkpoints from',os.path.join(ckpt_dir, 'checkpoints/chkpt-{0}'.format(num_ites)))
  
      normalized_embedding = run_embedding(sess,path_embedding_data,embedding_size)
      path_codebook = os.path.join(path_embedding_data,'edgeLambda25' + '_codebook')
      np.save(path_codebook, normalized_embedding)