def do_test(self, sess, summary_writer, step, names=None):
        '''execute computation of the inference
        a fast version of inference
        '''
        # during training
        """
        self.uvd_pts = uvd_pts
        self.xyz_pts = xyz_pts
        self.val_dms = dms
        self.est_hms = est_hms
        self.gt_pose = poses
        self.gt_uvd_pts = gt_uvd_pts
        """
        if names is None:
            f = open(self._log_path, 'a')
            summary_str, gt_vals, xyz_vals = sess.run(
                [self.val_summary_op, self.gt_pose, self.xyz_pts])
            summary_writer.add_summary(summary_str, step)

            maxJntError = []
            f.write('[%s] step %d\n' % (datetime.now(), step))
            for xyz_val, gt_val in zip(xyz_vals, gt_vals):
                maxJntError.append(Evaluation.maxJntError(xyz_val, gt_val))
                diff = (xyz_val - gt_val).reshape(-1, 3)
                dist = alg.norm(diff, axis=1).reshape(-1, 1)
                error_mat = np.concatenate((diff, dist), axis=1)
                print(error_mat)
                f.write(np.array_str(error_mat) + '\n')
            print('validate error:', maxJntError)
            f.write('validation error: {}\n'.format(maxJntError))
            f.flush()
            f.close()
            return

        if step % 100 == 0:
            summary_str, xyz_vals, gt_vals, names, val_dms_v, gt_uvd_pts_v, uvd_pts_v = sess.run(
                [
                    self.val_summary_op, self.xyz_pts, self.gt_pose, names,
                    self.val_dms, self.gt_uvd_pts, self.uvd_pts
                ])
            summary_writer.add_summary(summary_str, step)

            maxJntError = []
            for xyz_val, gt_val in zip(xyz_vals, gt_vals):
                maxJntError.append(Evaluation.maxJntError(xyz_val, gt_val))
                diff = (xyz_val - gt_val).reshape(-1, 3)
                dist = alg.norm(diff, axis=1).reshape(-1, 1)
                print(np.concatenate((diff, dist), axis=1))
            print('[step: %d]test error:' % step, maxJntError)
            print('---\n')
            return gt_vals, xyz_vals, names, val_dms_v, gt_uvd_pts_v, uvd_pts_v

        gt_vals, xyz_vals, names, val_dms_v, gt_uvd_pts_v, uvd_pts_v  = \
            sess.run([self.gt_pose, self.xyz_pts, names, self.val_dms, self.gt_uvd_pts, self.uvd_pts])

        return gt_vals, xyz_vals, names, val_dms_v, gt_uvd_pts_v, uvd_pts_v
Esempio n. 2
0
import sys
import numpy as np
from data.evaluation import Evaluation
xyz_gt_list = np.loadtxt("xyz_gt_list_all.txt")
xyz_val_list1 = np.loadtxt(
    "/home/chen/Documents/GNN_demo/train_values_all_1.txt")
xyz_val_list1 = xyz_val_list1.reshape([-1, 42])
xyz_val_list2 = np.loadtxt(
    "/home/chen/Documents/GNN_demo/train_values_all_2.txt")
xyz_val_list2 = xyz_val_list2.reshape([-1, 42])
xyz_val_list3 = np.loadtxt(
    "/home/chen/Documents/GNN_demo/train_values_all_3.txt")
xyz_val_list3 = xyz_val_list3.reshape([-1, 42])
xyz_val_list4 = np.loadtxt(
    "/home/chen/Documents/GNN_demo/train_values_all_4.txt")
xyz_val_list4 = xyz_val_list4.reshape([-1, 42])
xyz_val_list = np.concatenate(
    (xyz_val_list1, xyz_val_list2, xyz_val_list3, xyz_val_list4), axis=0)
xyz_val_list_ori = np.loadtxt(
    "/home/chen/Documents/denseReg-master/model/xyz_val_test_all.txt")
meanJntError = []
err_path = "/home/chen/Documents/denseReg-master/exp/train_cache/saved/GNN/_error.txt"
for i in range(8252):
    #xyz_val = xyz_val_list[i,:]#图网络优化后的输出,误差test10.060924231540694mm
    xyz_val = xyz_val_list_ori[i, :]  #原始输出,误差10.233949127173911mm
    gt_val = xyz_gt_list[i, :]
    meanJntError.append(Evaluation.meanJntError(xyz_val, gt_val))
Evaluation.plotError(meanJntError, err_path)
Esempio n. 3
0
    '--initial-state',
    '-s',
    type=int,
    default=1,
    help=
    'Defines the initial state (i.e. initial city, where teams are spawned)')
parser.add_argument(
    '--local-search',
    '-l',
    choices=LocalSearchFactory.choices(),
    default=None,
    help='Choose an available local search method to improve output paths')

args = parser.parse_args()

evaluation = Evaluation.minmax()
loader = TSPLIBLoader(args.problem)
initializer = Initializer.fixed_state(args.initial_state)
local_search = LocalSearchFactory.build(args.local_search)
stop_criterion = StopCriterion.iteration_limit(args.max_iterations)
taco = TeamAntColonyOptimization(args.num_teams, args.team_size, initializer,
                                 evaluation)

track_base = 'm{}_{}minmax_track.png'
solution_base = '{}2opt_m{}_{}minmax.png'
solutions, score, track = taco.optimize(loader, stop_criterion, local_search)

plot_evolution_track(track_base.format(args.team_size, score), track)
loader.plot(solution_base.format(loader.name, args.team_size, score),
            solutions=solutions)
Esempio n. 4
0
def test(model, selected_step):
    with tf.Graph().as_default():
        total_test_num = model.val_dataset.exact_num

        dms, poses, cfgs, coms, names = model.batch_input_test(
            model.val_dataset)
        model.test(dms, poses, cfgs, coms, reuse_variables=None)

        # dms, poses, names = model.batch_input_test(model.val_dataset)
        # model.test(dms, poses, reuse_variables=None)

        sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                                log_device_placement=False))

        init_op = tf.group(tf.global_variables_initializer(),
                           tf.local_variables_initializer())
        sess.run(init_op)

        if selected_step is not None:
            checkpoint_path = os.path.join(model.train_dir,
                                           'model.ckpt-%d' % selected_step)
            saver = tf.train.Saver(tf.global_variables())
            saver.restore(sess, checkpoint_path)
            print('[test_model]model has been resotored from %s' %
                  checkpoint_path)

        tf.train.start_queue_runners(sess=sess)
        summary_writer = tf.summary.FileWriter(model.summary_dir + '_' +
                                               model.val_dataset.subset,
                                               graph=sess.graph)

        res_path = os.path.join(
            model.train_dir,
            '%s-%s-result' % (model.val_dataset.subset, datetime.now()))
        res_path = res_path.replace(' ', '_')
        res_path = res_path.replace(':', '_')

        res_txt_path = res_path + '.txt'
        if os.path.exists(res_txt_path):
            os.remove(res_txt_path)
        err_path = res_path + '_error.txt'
        f = open(res_txt_path, 'w')

        # res_vid_path = res_path+'.avi'
        # codec = cv2.cv.CV_FOURCC('X','V','I','D')
        # the output size is defined by the visualization tool of matplotlib
        # vid = cv2.VideoWriter(res_vid_path, codec, 25, (640, 480))

        print('[test_model]begin test')
        test_num = 0
        step = 0
        maxJntError = []
        while True:
            start_time = time.time()
            try:
                gt_vals, xyz_vals, name_vals = model.do_test(
                    sess, summary_writer, step, names)
            except tf.errors.OutOfRangeError:
                print('run out of range')
                break

            duration = time.time() - start_time

            for xyz_val, gt_val, name_val in zip(xyz_vals, gt_vals, name_vals):
                maxJntError.append(Evaluation.maxJntError(xyz_val, gt_val))

                xyz_val = xyz_val.tolist()
                res_str = '%s\t%s\n' % (name_val, '\t'.join(
                    format(pt, '.4f') for pt in xyz_val))
                res_str = res_str.replace('/', '\\')
                f.write(res_str)
                # vid.write(vis_val)
                test_num += 1
                if test_num >= total_test_num:
                    print('finish test')
                    f.close()
                    Evaluation.plotError(maxJntError, err_path)
                    return
            f.flush()

            if step % 101 == 0:
                print('[%s]: %d/%d computed, with %.2fs' %
                      (datetime.now(), step, model.max_steps, duration))

            step += 1

        print('finish test')
        f.close()
        Evaluation.plotError(maxJntError, 'result.txt')
Esempio n. 5
0
    def test(self, test_stream, desc='dummy', modelIdx='-1'):
        cache_dir = os.path.join(
            globalConfig.model_dir,
            'gan_render/%s_%s' % (globalConfig.dataset, desc))

        if not os.path.exists(cache_dir):
            raise IOError('%s does not exists' % cache_dir)

        img_dir = os.path.join(cache_dir, 'test_img')
        if os.path.exists(img_dir):
            shutil.rmtree(img_dir)
        os.mkdir(img_dir)

        model_path = os.path.join(cache_dir, 'params', modelIdx)
        self.loadParam(model_path)

        idx, total_time, recons_err = 0, 0, 0
        maxJntError = []

        codec = cv2.cv.CV_FOURCC('X', 'V', 'I', 'D')
        vid = cv2.VideoWriter(os.path.join(img_dir, 'res.avi'), codec, 25,
                              (128 * 4, 128))
        for skel, orig, trans, com, depth in\
            test_stream.iterate(batchsize=1, shuffle=False):
            noise = np.zeros((1, self.pose_z_dim), np.float32)
            reco_depth = self.render_fn(skel, orig, noise)
            reco_pose = self.vae_reco_fn(skel, noise)
            pose = self.resumePose(reco_pose[0], orig[0])
            fake_img = self.visPair(reco_depth[0], pose, trans[0], com[0],
                                    50.0)

            gt_pose = self.resumePose(skel[0], orig[0])
            real_img = self.visPair(depth[0], gt_pose, trans[0], com[0], 50.0)

            # real calculation part
            start_time = time.time()
            est_z = self.z_est_fn(depth)
            est_z.shape = (23, )
            est_z, est_orig = est_z[:20], est_z[20:]
            est_z.shape = (1, 20)
            est_orig.shape = (1, 3)
            est_pose = self.pose_decode_fn(est_z)
            end_time = time.time()

            est_depth = self.render_fn(est_pose, est_orig, noise)
            est_pose = self.resumePose(est_pose[0], est_orig[0])
            est_img = self.visPair(est_depth[0], est_pose, trans[0], com[0],
                                   50.0)
            com_img = self.visPair(depth[0], est_pose, trans[0], com[0], 50.0)

            recons_err += (abs(reco_depth - depth)).mean()

            recons_depth = np.hstack((real_img, fake_img, est_img, com_img))
            # cv2.imwrite(os.path.join(img_dir,'%d_0.jpg'%(idx)),\
            # recons_depth.astype('uint8'))
            idx += 1
            maxJntError.append(Evaluation.maxJntError(gt_pose, est_pose))
            total_time += end_time - start_time
            vid.write(recons_depth.astype('uint8'))

        print 'average running time = %fs' % (total_time / idx)
        print 'average reconstruction error  = %f' % (recons_err / idx)
        fig_path = os.path.join(img_dir, 'maxError.txt')
        Evaluation.plotError(maxJntError, fig_path)
        vid.release()
Esempio n. 6
0
def test(model, selected_step):
    with tf.Graph().as_default():
        total_test_num = model.val_dataset.exact_num
        #获得原始数据,唯一的处理就是把深度图crop了一下
        dms, poses, cfgs, coms, names = model.batch_input_test(
            model.val_dataset)
        model.test(dms, poses, cfgs, coms, reuse_variables=None)

        # dms, poses, names = model.batch_input_test(model.val_dataset)
        # model.test(dms, poses, reuse_variables=None)
        gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95)

        sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options,
                                                allow_soft_placement=True,
                                                log_device_placement=False))

        init_op = tf.group(tf.global_variables_initializer(),
                           tf.local_variables_initializer())
        sess.run(init_op)

        if selected_step is not None:
            checkpoint_path = os.path.join(model.train_dir,
                                           'model.ckpt-%d' % selected_step)
            saver = tf.train.Saver(tf.global_variables())
            saver.restore(sess, checkpoint_path)
            print('[test_model]model has been resotored from %s' %
                  checkpoint_path)

        tf.train.start_queue_runners(sess=sess)
        summary_writer = tf.summary.FileWriter(model.summary_dir + '_' +
                                               model.val_dataset.subset,
                                               graph=sess.graph)

        res_path = os.path.join(
            model.train_dir,
            '%s-%s-result' % (model.val_dataset.subset, datetime.now()))
        res_path = res_path.replace(' ', '_')

        res_txt_path = res_path + '.txt'
        if os.path.exists(res_txt_path):
            os.remove(res_txt_path)
        err_path = res_path + '_error.txt'
        f = open(res_txt_path, 'w')

        # res_vid_path = res_path+'.avi'
        # codec = cv2.cv.CV_FOURCC('X','V','I','D')
        # the output size is defined by the visualization tool of matplotlib
        # vid = cv2.VideoWriter(res_vid_path, codec, 25, (640, 480))

        print('[test_model]begin test')
        test_num = 0
        step = 0
        meanJntError = []
        xyz_val_list = []
        xyz_gt_list = []
        while True:
            start_time = time.time()
            try:
                gt_vals, xyz_vals, name_vals, val_dms_v, gt_uvd_pts_v, uvd_pts_v = model.do_test(
                    sess, summary_writer, step, names)
            except tf.errors.OutOfRangeError:
                print('run out of range')
                break

            duration = time.time() - start_time

            for xyz_val, gt_val, name_val, val_dms_v1, gt_uvd_pts_v1, uvd_pts_v1 in zip(
                    xyz_vals, gt_vals, name_vals, val_dms_v, gt_uvd_pts_v,
                    uvd_pts_v):
                #maxJntError.append(Evaluation.maxJntError(xyz_val, gt_val))

                #figure_joint_skeleton2(np.squeeze(val_dms_v1),gt_uvd_pts_v1,test_num,"gt")#.savefig("/home/chen/Documents/denseReg-master/exp/train_cache/saved/pretrain/image/"+str(test_num).zfill(7)+"_gt.png")
                #figure_joint_skeleton2(np.squeeze(val_dms_v1), uvd_pts_v1,test_num,"pt")#.savefig("/home/chen/Documents/denseReg-master/exp/train_cache/saved/pretrain/image/"+str(test_num).zfill(7)+"_pt.png")

                meanJntError.append(Evaluation.meanJntError(xyz_val, gt_val))
                xyz_val_list.append(xyz_val[np.newaxis, :])
                xyz_gt_list.append(gt_val[np.newaxis, :])
                xyz_val = xyz_val.tolist()
                res_str = '%s\t%s\n' % (name_val, '\t'.join(
                    format(pt, '.4f') for pt in xyz_val))
                res_str = res_str.replace('/', '\\')
                f.write(res_str)
                # vid.write(vis_val)
                test_num += 1
                if test_num >= total_test_num:
                    xyz_gt_list = np.concatenate(xyz_gt_list, axis=0)
                    np.savetxt("xyz_gt_test_5.txt", xyz_gt_list, fmt="%.5f")
                    np.savetxt("xyz_gt_test_all.txt",
                               xyz_gt_list)  # 缺省按照'%.18e'格式保存数据,以空格分隔
                    xyz_val_list = np.concatenate(xyz_val_list, axis=0)
                    np.savetxt("xyz_val_test_5.txt", xyz_val_list, fmt="%.5f")
                    np.savetxt("xyz_val_test_all.txt",
                               xyz_val_list)  # 缺省按照'%.18e'格式保存数据,以空格分隔
                    #xyz_val_list2 = np.loadtxt("a.txt")
                    print('finish test')
                    f.close()
                    Evaluation.plotError(meanJntError, err_path)

                    return
            f.flush()

            if step % 101 == 0:
                print('[%s]: %d/%d computed, with %.2fs' %
                      (datetime.now(), step, model.max_steps, duration))

            step += 1