示例#1
0
    def test_single_camera_point_positions(self):
        """Point positions for a single camera case"""

        num_cams = 1
        # prepare MultimediaParams
        cpar_file = b'testing_fodder/single_cam/parameters/ptv.par'
        vpar_file = b'testing_fodder/single_cam/parameters/criteria.par'
        cpar = ControlParams(num_cams)
        cpar.read_control_par(cpar_file)
        mult_params = cpar.get_multimedia_params()

        vpar = VolumeParams()
        vpar.read_volume_par(vpar_file)

        ori_name = b'testing_fodder/single_cam/calibration/cam_1.tif.ori'
        add_name = b'testing_fodder/single_cam/calibration/cam_1.tif.addpar'
        calibs = []


        # read calibration for each camera from files
        new_cal = Calibration()
        new_cal.from_file(ori_file=ori_name, add_file=add_name)
        calibs.append(new_cal)


        # 3d point
        points = np.array([[1, 1, 0],
                           [-1, -1, 0]], dtype=float)

        targs_plain = []
        targs_jigged = []


        jigg_amp = 0.4


        new_plain_targ = image_coordinates(
            points, calibs[0], mult_params)
        targs_plain.append(new_plain_targ)

        jigged_points = points - np.r_[0, jigg_amp, 0]

        new_jigged_targs = image_coordinates(
            jigged_points, calibs[0], mult_params)
        targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1,0,2)
        targs_jigged = np.array(targs_jigged).transpose(1,0,2)
        skew_dist_plain = point_positions(targs_plain, cpar, calibs, vpar)
        skew_dist_jigged = point_positions(targs_jigged, cpar, calibs, vpar)

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(np.linalg.norm(jigged_points - skew_dist_jigged[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position after jigging.')
 def setUp(self):
     self.input_volume_par_file_name = "testing_fodder/volume_parameters/volume.par"
     self.temp_output_directory = "testing_fodder/volume_parameters/testing_output"
     
     # create a temporary output directory (will be deleted by the end of test)
     if not os.path.exists(self.temp_output_directory):
         os.makedirs(self.temp_output_directory)
         
     # create an instance of VolumeParams class
     self.vol_obj = VolumeParams()
    def test_single_camera_point_positions(self):
        """Point positions for a single camera case"""

        num_cams = 1
        # prepare MultimediaParams
        cpar_file = b'testing_fodder/single_cam/parameters/ptv.par'
        vpar_file = b'testing_fodder/single_cam/parameters/criteria.par'
        cpar = ControlParams(num_cams)
        cpar.read_control_par(cpar_file)
        mult_params = cpar.get_multimedia_params()

        vpar = VolumeParams()
        vpar.read_volume_par(vpar_file)

        ori_name = b'testing_fodder/single_cam/calibration/cam_1.tif.ori'
        add_name = b'testing_fodder/single_cam/calibration/cam_1.tif.addpar'
        calibs = []

        # read calibration for each camera from files
        new_cal = Calibration()
        new_cal.from_file(ori_file=ori_name, add_file=add_name)
        calibs.append(new_cal)

        # 3d point
        points = np.array([[1, 1, 0], [-1, -1, 0]], dtype=float)

        targs_plain = []
        targs_jigged = []

        jigg_amp = 0.4

        new_plain_targ = image_coordinates(points, calibs[0], mult_params)
        targs_plain.append(new_plain_targ)

        jigged_points = points - np.r_[0, jigg_amp, 0]

        new_jigged_targs = image_coordinates(jigged_points, calibs[0],
                                             mult_params)
        targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1, 0, 2)
        targs_jigged = np.array(targs_jigged).transpose(1, 0, 2)
        skew_dist_plain = point_positions(targs_plain, cpar, calibs, vpar)
        skew_dist_jigged = point_positions(targs_jigged, cpar, calibs, vpar)

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(
                np.linalg.norm(jigged_points -
                               skew_dist_jigged[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position after jigging.')
    def setUp(self):
        self.input_ori_file_name = b'testing_fodder/calibration/cam1.tif.ori'
        self.input_add_file_name = b'testing_fodder/calibration/cam2.tif.addpar'
        self.control_file_name = b'testing_fodder/control_parameters/control.par'
        self.volume_file_name = b'testing_fodder/corresp/criteria.par'

        self.calibration = Calibration()
        self.calibration.from_file(self.input_ori_file_name,
                                   self.input_add_file_name)
        self.control = ControlParams(4)
        self.control.read_control_par(self.control_file_name)
        self.vpar = VolumeParams()
        self.vpar.read_volume_par(self.volume_file_name)
示例#5
0
 def test_rich_compare(self):
     self.vol_obj2 = VolumeParams()
     self.vol_obj2.read_volume_par(self.input_volume_par_file_name)
     self.vol_obj3 = VolumeParams()
     self.vol_obj3.read_volume_par(self.input_volume_par_file_name)
     self.failUnless(self.vol_obj2 == self.vol_obj3)
     self.failIf(self.vol_obj2 != self.vol_obj3)
     
     self.vol_obj2.set_cn(-999)
     self.failUnless(self.vol_obj2 != self.vol_obj3)
     self.failIf(self.vol_obj2 == self.vol_obj3)
     
     with self.assertRaises(TypeError):
         var = (self.vol_obj2 < self.vol_obj3)
 def test_rich_compare(self):
     self.vol_obj2 = VolumeParams()
     self.vol_obj2.read_volume_par(self.input_volume_par_file_name)
     self.vol_obj3 = VolumeParams()
     self.vol_obj3.read_volume_par(self.input_volume_par_file_name)
     self.failUnless(self.vol_obj2 == self.vol_obj3)
     self.failIf(self.vol_obj2 != self.vol_obj3)
     
     self.vol_obj2.set_cn(-999)
     self.failUnless(self.vol_obj2 != self.vol_obj3)
     self.failIf(self.vol_obj2 == self.vol_obj3)
     
     with self.assertRaises(TypeError):
         var = (self.vol_obj2 < self.vol_obj3)
示例#7
0
 def test_full_corresp(self):
     """Full scene correspondences"""
     print "about to dump core"
     cpar = ControlParams(4)
     cpar.read_control_par("testing_fodder/corresp/control.par")
     vpar = VolumeParams()
     vpar.read_volume_par("testing_fodder/corresp/criteria.par")
     
     # Cameras are at so high angles that opposing cameras don't see each 
     # other in the normal air-glass-water setting.
     cpar.get_multimedia_params().set_layers([1.0001], [1.])
     cpar.get_multimedia_params().set_n3(1.0001)
     
     cals = []
     img_pts = []
     corrected = []
     for c in xrange(4):
         cal = Calibration()
         cal.from_file(
             "testing_fodder/calibration/sym_cam%d.tif.ori" % (c + 1),
             "testing_fodder/calibration/cam1.tif.addpar")
         cals.append(cal)
     
         # Generate test targets.
         targs = TargetArray(16)
         for row, col in np.ndindex(4, 4):
             targ_ix = row*4 + col
             # Avoid symmetric case:
             if (c % 2):
                 targ_ix = 15 - targ_ix
             targ = targs[targ_ix]
             
             pos3d = 10*np.array([[col, row, 0]], dtype=np.float64)
             pos2d = image_coordinates(
                 pos3d, cal, cpar.get_multimedia_params())
             targ.set_pos(convert_arr_metric_to_pixel(pos2d, cpar)[0])
             
             targ.set_pnr(targ_ix)
             targ.set_pixel_counts(25, 5, 5)
             targ.set_sum_grey_value(10)
         
         img_pts.append(targs)
         mc = MatchedCoords(targs, cpar, cal)
         corrected.append(mc)
     
     sorted_pos, sorted_corresp, num_targs = correspondences(
         img_pts, corrected, cals, vpar, cpar)
     self.failUnlessEqual(num_targs, 16)
示例#8
0
    def test_full_corresp(self):
        """Full scene correspondences"""
        cpar = ControlParams(4)
        cpar.read_control_par(r"testing_fodder/corresp/control.par")
        vpar = VolumeParams()
        vpar.read_volume_par(r"testing_fodder/corresp/criteria.par")

        # Cameras are at so high angles that opposing cameras don't see each
        # other in the normal air-glass-water setting.
        cpar.get_multimedia_params().set_layers([1.0001], [1.])
        cpar.get_multimedia_params().set_n3(1.0001)

        cals = []
        img_pts = []
        corrected = []
        for c in xrange(4):
            cal = Calibration()
            cal.from_file(
                "testing_fodder/calibration/sym_cam%d.tif.ori" % (c + 1),
                "testing_fodder/calibration/cam1.tif.addpar")
            cals.append(cal)

            # Generate test targets.
            targs = TargetArray(16)
            for row, col in np.ndindex(4, 4):
                targ_ix = row * 4 + col
                # Avoid symmetric case:
                if (c % 2):
                    targ_ix = 15 - targ_ix
                targ = targs[targ_ix]

                pos3d = 10 * np.array([[col, row, 0]], dtype=np.float64)
                pos2d = image_coordinates(pos3d, cal,
                                          cpar.get_multimedia_params())
                targ.set_pos(convert_arr_metric_to_pixel(pos2d, cpar)[0])

                targ.set_pnr(targ_ix)
                targ.set_pixel_counts(25, 5, 5)
                targ.set_sum_grey_value(10)

            img_pts.append(targs)
            mc = MatchedCoords(targs, cpar, cal)
            corrected.append(mc)

        sorted_pos, sorted_corresp, num_targs = correspondences(
            img_pts, corrected, cals, vpar, cpar)

        self.failUnlessEqual(num_targs, 16)
示例#9
0
    def test_single_cam_corresp(self):
        """Single camera correspondence"""
        cpar = ControlParams(1)
        cpar.read_control_par("testing_fodder/single_cam/parameters/ptv.par")
        vpar = VolumeParams()
        vpar.read_volume_par(
            "testing_fodder/single_cam/parameters/criteria.par")

        # Cameras are at so high angles that opposing cameras don't see each
        # other in the normal air-glass-water setting.
        cpar.get_multimedia_params().set_layers([1.], [1.])
        cpar.get_multimedia_params().set_n3(1.)

        cals = []
        img_pts = []
        corrected = []
        cal = Calibration()
        cal.from_file(
            "testing_fodder/single_cam/calibration/cam_1.tif.ori",
            "testing_fodder/single_cam/calibration/cam_1.tif.addpar")
        cals.append(cal)

        # Generate test targets.
        targs = TargetArray(9)
        for row, col in np.ndindex(3, 3):
            targ_ix = row * 3 + col
            targ = targs[targ_ix]

            pos3d = 10 * np.array([[col, row, 0]], dtype=np.float64)
            pos2d = image_coordinates(pos3d, cal, cpar.get_multimedia_params())
            targ.set_pos(convert_arr_metric_to_pixel(pos2d, cpar)[0])

            targ.set_pnr(targ_ix)
            targ.set_pixel_counts(25, 5, 5)
            targ.set_sum_grey_value(10)

            img_pts.append(targs)
            mc = MatchedCoords(targs, cpar, cal)
            corrected.append(mc)

        sorted_pos, sorted_corresp, num_targs = correspondences(
            img_pts, corrected, cals, vpar, cpar)

        self.failUnlessEqual(num_targs, 9)
示例#10
0
    def test_single_cam_corresp(self):
        """Single camera correspondence"""
        cpar = ControlParams(1)
        cpar.read_control_par(b"testing_fodder/single_cam/parameters/ptv.par")
        vpar = VolumeParams()
        vpar.read_volume_par(b"testing_fodder/single_cam/parameters/criteria.par")
        
        # Cameras are at so high angles that opposing cameras don't see each 
        # other in the normal air-glass-water setting.
        cpar.get_multimedia_params().set_layers([1.], [1.])
        cpar.get_multimedia_params().set_n3(1.)
        
        cals = []
        img_pts = []
        corrected = []
        cal = Calibration()
        cal.from_file(
            b"testing_fodder/single_cam/calibration/cam_1.tif.ori",
            b"testing_fodder/single_cam/calibration/cam_1.tif.addpar")
        cals.append(cal)
        
        # Generate test targets.
        targs = TargetArray(9)
        for row, col in np.ndindex(3, 3):
            targ_ix = row*3 + col
            targ = targs[targ_ix]
            
            pos3d = 10*np.array([[col, row, 0]], dtype=np.float64)
            pos2d = image_coordinates(
                pos3d, cal, cpar.get_multimedia_params())
            targ.set_pos(convert_arr_metric_to_pixel(pos2d, cpar)[0])
            
            targ.set_pnr(targ_ix)
            targ.set_pixel_counts(25, 5, 5)
            targ.set_sum_grey_value(10)
            
            img_pts.append(targs)
            mc = MatchedCoords(targs, cpar, cal)
            corrected.append(mc)
        
        _, _, num_targs = correspondences(
            img_pts, corrected, cals, vpar, cpar)

        self.failUnlessEqual(num_targs, 9)
示例#11
0
 def setUp(self):
     self.input_volume_par_file_name = "testing_fodder/volume_parameters/volume.par"
     self.temp_output_directory = "testing_fodder/volume_parameters/testing_output"
     
     # create a temporary output directory (will be deleted by the end of test)
     if not os.path.exists(self.temp_output_directory):
         os.makedirs(self.temp_output_directory)
         
     # create an instance of VolumeParams class
     self.vol_obj = VolumeParams()
示例#12
0
def py_determination_proc_c(n_cams, sorted_pos, sorted_corresp, corrected):
    """ Returns 3d positions """

    # Control parameters
    cpar = ControlParams(n_cams)
    cpar.read_control_par(b'parameters/ptv.par')

    # Volume parameters
    vpar = VolumeParams()
    vpar.read_volume_par(b'parameters/criteria.par')

    cals =[]
    for i_cam in range(n_cams):
        cal = Calibration()
        tmp = cpar.get_cal_img_base_name(i_cam)
        cal.from_file(tmp + b'.ori', tmp + b'.addpar')
        cals.append(cal)


    # Distinction between quad/trip irrelevant here.
    sorted_pos = np.concatenate(sorted_pos, axis=1)
    sorted_corresp = np.concatenate(sorted_corresp, axis=1)


    flat = np.array([corrected[i].get_by_pnrs(sorted_corresp[i]) \
                     for i in range(len(cals))])
    pos, rcm = point_positions(
        flat.transpose(1,0,2), cpar, cals, vpar)

    if len(cals) < 4:
        print_corresp = -1*np.ones((4,sorted_corresp.shape[1]))
        print_corresp[:len(cals),:] = sorted_corresp
    else:
        print_corresp = sorted_corresp

    # Save rt_is in a temporary file
    fname = b"".join([default_naming['corres'],b'.123456789']) # hard-coded frame number
    with open(fname, 'w') as rt_is:
        rt_is.write(str(pos.shape[0]) + '\n')
        for pix, pt in enumerate(pos):
            pt_args = (pix + 1,) + tuple(pt) + tuple(print_corresp[:,pix])
            rt_is.write("%4d %9.3f %9.3f %9.3f %4d %4d %4d %4d\n" % pt_args)
示例#13
0
 def test_init_kwargs(self):
     """Initialize volume parameters with keyword arguments"""
     xlay = numpy.array([111.1, 222.2])
     zlay = [r_[333.3, 555.5], r_[444.4, 666.6]]
     zmin, zmax = zip(*zlay)
     
     vol_obj = VolumeParams(x_span=xlay, z_spans=zlay, 
         pixels_tot=1, pixels_x=2, pixels_y=3, 
         ref_gray=4, epipolar_band=5, min_correlation=6)
     
     numpy.testing.assert_array_equal(xlay, vol_obj.get_X_lay())
     numpy.testing.assert_array_equal(zmin, vol_obj.get_Zmin_lay())
     numpy.testing.assert_array_equal(zmax, vol_obj.get_Zmax_lay())
     
     self.failUnless(vol_obj.get_cn() == 1)
     self.failUnless(vol_obj.get_cnx() == 2)
     self.failUnless(vol_obj.get_cny() == 3)
     self.failUnless(vol_obj.get_csumg() == 4)
     self.failUnless(vol_obj.get_eps0() == 5)
     self.failUnless(vol_obj.get_corrmin() == 6)
示例#14
0
    def setUp(self):
        self.input_ori_file_name = b'testing_fodder/calibration/cam1.tif.ori'
        self.input_add_file_name = b'testing_fodder/calibration/cam2.tif.addpar'
        self.control_file_name = b'testing_fodder/control_parameters/control.par'
        self.volume_file_name = b'testing_fodder/corresp/criteria.par'

        self.calibration = Calibration()
        self.calibration.from_file(
            self.input_ori_file_name, self.input_add_file_name)
        self.control = ControlParams(4)
        self.control.read_control_par(self.control_file_name)
        self.vpar = VolumeParams()
        self.vpar.read_volume_par(self.volume_file_name)
示例#15
0
def py_determination_proc_c(n_cams, sorted_pos, sorted_corresp, corrected):
    """ Returns 3d positions """

    # Control parameters
    cpar = ControlParams(n_cams)
    cpar.read_control_par('parameters/ptv.par')

    # Volume parameters
    vpar = VolumeParams()
    vpar.read_volume_par('parameters/criteria.par')

    cals = []
    for i_cam in xrange(n_cams):
        cal = Calibration()
        tmp = cpar.get_cal_img_base_name(i_cam)
        cal.from_file(tmp + '.ori', tmp + '.addpar')
        cals.append(cal)

    # Distinction between quad/trip irrelevant here.
    sorted_pos = np.concatenate(sorted_pos, axis=1)
    sorted_corresp = np.concatenate(sorted_corresp, axis=1)


    flat = np.array([corrected[i].get_by_pnrs(sorted_corresp[i]) \
                     for i in xrange(len(cals))])
    pos, rcm = point_positions(flat.transpose(1, 0, 2), cpar, cals, vpar)

    if len(cals) == 1:  # single camera case
        sorted_corresp = np.tile(sorted_corresp, (4, 1))
        sorted_corresp[1:, :] = -1

    # Save rt_is in a temporary file
    frame = 123456789  # just a temporary workaround. todo: think how to write
    with open(default_naming['corres'] + '.' + str(frame), 'w') as rt_is:
        rt_is.write(str(pos.shape[0]) + '\n')
        for pix, pt in enumerate(pos):
            pt_args = (pix + 1, ) + tuple(pt) + tuple(sorted_corresp[:, pix])
            rt_is.write("%4d %9.3f %9.3f %9.3f %4d %4d %4d %4d\n" % pt_args)
示例#16
0
def py_start_proc_c(n_cams):
    """ Read parameters """

    # Control parameters
    cpar = ControlParams(n_cams)
    cpar.read_control_par(b'parameters/ptv.par')

    # Sequence parameters
    spar = SequenceParams(num_cams=n_cams)
    spar.read_sequence_par(b'parameters/sequence.par', n_cams)

    # Volume parameters
    vpar = VolumeParams()
    vpar.read_volume_par(b'parameters/criteria.par')

    # Tracking parameters
    track_par = TrackingParams()
    track_par.read_track_par(b'parameters/track.par')

    # Target parameters
    tpar = TargetParams(n_cams)
    tpar.read(b'parameters/targ_rec.par')

    # Examine parameters, multiplane (single plane vs combined calibration)
    epar = par.ExamineParams()
    epar.read()

    # Calibration parameters
    cals = []
    for i_cam in range(n_cams):
        cal = Calibration()
        tmp = cpar.get_cal_img_base_name(i_cam)
        cal.from_file(tmp + b'.ori', tmp + b'.addpar')
        cals.append(cal)

    return cpar, spar, vpar, track_par, tpar, cals, epar
    def test_two_cameras(self):
        ori_tmpl = "testing_fodder/calibration/sym_cam{cam_num}.tif.ori"
        add_file = "testing_fodder/calibration/cam1.tif.addpar"

        orig_cal = Calibration()
        orig_cal.from_file(
            ori_tmpl.format(cam_num=1).encode(), add_file.encode())
        proj_cal = Calibration()
        proj_cal.from_file(
            ori_tmpl.format(cam_num=3).encode(), add_file.encode())

        # reorient cams:
        orig_cal.set_angles(np.r_[0., -np.pi / 4., 0.])
        proj_cal.set_angles(np.r_[0., 3 * np.pi / 4., 0.])

        cpar = ControlParams(4)
        cpar.read_control_par(b"testing_fodder/corresp/control.par")
        sens_size = cpar.get_image_size()

        vpar = VolumeParams()
        vpar.read_volume_par(b"testing_fodder/corresp/criteria.par")
        vpar.set_Zmin_lay([-10, -10])
        vpar.set_Zmax_lay([10, 10])

        mult_params = cpar.get_multimedia_params()
        mult_params.set_n1(1.)
        mult_params.set_layers(np.array([1.]), np.array([1.]))
        mult_params.set_n3(1.)

        # Central point translates to central point because cameras point
        # directly at each other.
        mid = np.r_[sens_size] / 2.
        line = epipolar_curve(mid, orig_cal, proj_cal, 5, cpar, vpar)
        self.failUnless(np.all(abs(line - mid) < 1e-6))

        # An equatorial point draws a latitude.
        line = epipolar_curve(mid - np.r_[100., 0.], orig_cal, proj_cal, 5,
                              cpar, vpar)
        np.testing.assert_array_equal(np.argsort(line[:, 0]),
                                      np.arange(5)[::-1])
        self.failUnless(np.all(abs(line[:, 1] - mid[1]) < 1e-6))
示例#18
0
    def setUp(self):
        with open("testing_fodder/track/conf.yaml") as f:
            yaml_conf = yaml.load(f)
        seq_cfg = yaml_conf['sequence']

        cals = []
        img_base = []
        for cix, cam_spec in enumerate(yaml_conf['cameras']):
            cam_spec.setdefault('addpar_file', None)
            cal = Calibration()
            cal.from_file(cam_spec['ori_file'], cam_spec['addpar_file'])
            cals.append(cal)
            img_base.append(seq_cfg['targets_template'].format(cam=cix + 1))

        cpar = ControlParams(len(yaml_conf['cameras']), **yaml_conf['scene'])
        vpar = VolumeParams(**yaml_conf['correspondences'])
        tpar = TrackingParams(**yaml_conf['tracking'])
        spar = SequenceParams(image_base=img_base,
                              frame_range=(seq_cfg['first'], seq_cfg['last']))

        self.tracker = Tracker(cpar, vpar, tpar, spar, cals, framebuf_naming)
示例#19
0
 def test_two_cameras(self):
     ori_tmpl = "testing_fodder/calibration/sym_cam{cam_num}.tif.ori"
     add_file = "testing_fodder/calibration/cam1.tif.addpar"
     
     orig_cal = Calibration()
     orig_cal.from_file(ori_tmpl.format(cam_num=1).encode(), add_file.encode())
     proj_cal = Calibration()
     proj_cal.from_file(ori_tmpl.format(cam_num=3).encode(), add_file.encode())
     
     # reorient cams:
     orig_cal.set_angles(np.r_[0., -np.pi/4., 0.])
     proj_cal.set_angles(np.r_[0., 3*np.pi/4., 0.])
     
     cpar = ControlParams(4)
     cpar.read_control_par(b"testing_fodder/corresp/control.par")
     sens_size = cpar.get_image_size()
     
     vpar = VolumeParams()
     vpar.read_volume_par(b"testing_fodder/corresp/criteria.par")
     vpar.set_Zmin_lay([-10, -10])
     vpar.set_Zmax_lay([10, 10])
     
     mult_params = cpar.get_multimedia_params()
     mult_params.set_n1(1.)
     mult_params.set_layers(np.array([1.]), np.array([1.]))
     mult_params.set_n3(1.)
     
     # Central point translates to central point because cameras point 
     # directly at each other.
     mid = np.r_[sens_size]/2.
     line = epipolar_curve(mid, orig_cal, proj_cal, 5, cpar, vpar)
     self.failUnless(np.all(abs(line - mid) < 1e-6))
     
     # An equatorial point draws a latitude.
     line = epipolar_curve(
         mid - np.r_[100., 0.], orig_cal, proj_cal, 5, cpar, vpar)
     np.testing.assert_array_equal(np.argsort(line[:,0]), np.arange(5)[::-1])
     self.failUnless(np.all(abs(line[:,1] - mid[1]) < 1e-6))
示例#20
0
class Test_VolumeParams(unittest.TestCase):
    def setUp(self):
        self.input_volume_par_file_name = "testing_fodder/volume_parameters/volume.par"
        self.temp_output_directory = "testing_fodder/volume_parameters/testing_output"
        
        # create a temporary output directory (will be deleted by the end of test)
        if not os.path.exists(self.temp_output_directory):
            os.makedirs(self.temp_output_directory)
            
        # create an instance of VolumeParams class
        self.vol_obj = VolumeParams()
        
    def test_read_volume(self):
        # Fill the VolumeParams object with parameters from test file
        self.vol_obj.read_volume_par(self.input_volume_par_file_name)
        
        # check that all parameters are equal to the contents of test file
        numpy.testing.assert_array_equal(numpy.array([111.111, 222.222]), self.vol_obj.get_X_lay())
        numpy.testing.assert_array_equal(numpy.array([333.333, 444.444]), self.vol_obj.get_Zmin_lay())
        numpy.testing.assert_array_equal(numpy.array([555.555, 666.666]), self.vol_obj.get_Zmax_lay())
         
        self.failUnless(self.vol_obj.get_cnx() == 777.777)
        self.failUnless(self.vol_obj.get_cny() == 888.888)
        self.failUnless(self.vol_obj.get_cn() == 999.999)
        self.failUnless(self.vol_obj.get_csumg() == 1010.1010)
        self.failUnless(self.vol_obj.get_corrmin() == 1111.1111)
        self.failUnless(self.vol_obj.get_eps0() == 1212.1212)
        
    def test_setters(self):
        xlay = numpy.array([111.1, 222.2])
        self.vol_obj.set_X_lay(xlay)
        numpy.testing.assert_array_equal(xlay, self.vol_obj.get_X_lay())
        
        zmin = numpy.array([333.3, 444.4])
        self.vol_obj.set_Zmin_lay(zmin)
        numpy.testing.assert_array_equal(zmin, self.vol_obj.get_Zmin_lay())
        
        zmax = numpy.array([555.5, 666.6])
        self.vol_obj.set_Zmax_lay(zmax)
        numpy.testing.assert_array_equal(zmax, self.vol_obj.get_Zmax_lay())
        
        self.vol_obj.set_cn(1)
        self.failUnless(self.vol_obj.get_cn() == 1)
        
        self.vol_obj.set_cnx(2)
        self.failUnless(self.vol_obj.get_cnx() == 2)
        
        self.vol_obj.set_cny(3)
        self.failUnless(self.vol_obj.get_cny() == 3)
        
        self.vol_obj.set_csumg(4)
        self.failUnless(self.vol_obj.get_csumg() == 4)
        
        self.vol_obj.set_eps0(5)
        self.failUnless(self.vol_obj.get_eps0() == 5)
        
        self.vol_obj.set_corrmin(6)
        self.failUnless(self.vol_obj.get_corrmin() == 6)
    
    def test_init_kwargs(self):
        """Initialize volume parameters with keyword arguments"""
        xlay = numpy.array([111.1, 222.2])
        zlay = [r_[333.3, 555.5], r_[444.4, 666.6]]
        zmin, zmax = zip(*zlay)
        
        vol_obj = VolumeParams(x_span=xlay, z_spans=zlay, 
            pixels_tot=1, pixels_x=2, pixels_y=3, 
            ref_gray=4, epipolar_band=5, min_correlation=6)
        
        numpy.testing.assert_array_equal(xlay, vol_obj.get_X_lay())
        numpy.testing.assert_array_equal(zmin, vol_obj.get_Zmin_lay())
        numpy.testing.assert_array_equal(zmax, vol_obj.get_Zmax_lay())
        
        self.failUnless(vol_obj.get_cn() == 1)
        self.failUnless(vol_obj.get_cnx() == 2)
        self.failUnless(vol_obj.get_cny() == 3)
        self.failUnless(vol_obj.get_csumg() == 4)
        self.failUnless(vol_obj.get_eps0() == 5)
        self.failUnless(vol_obj.get_corrmin() == 6)
        
    # testing __richcmp__ comparison method of VolumeParams class
    def test_rich_compare(self):
        self.vol_obj2 = VolumeParams()
        self.vol_obj2.read_volume_par(self.input_volume_par_file_name)
        self.vol_obj3 = VolumeParams()
        self.vol_obj3.read_volume_par(self.input_volume_par_file_name)
        self.failUnless(self.vol_obj2 == self.vol_obj3)
        self.failIf(self.vol_obj2 != self.vol_obj3)
        
        self.vol_obj2.set_cn(-999)
        self.failUnless(self.vol_obj2 != self.vol_obj3)
        self.failIf(self.vol_obj2 == self.vol_obj3)
        
        with self.assertRaises(TypeError):
            var = (self.vol_obj2 < self.vol_obj3)
    
    def tearDown(self):
        # remove the testing output directory and its files
        shutil.rmtree(self.temp_output_directory)
 def test_init_kwargs(self):
     """Initialize volume parameters with keyword arguments"""
     xlay = numpy.array([111.1, 222.2])
     zlay = [r_[333.3, 555.5], r_[444.4, 666.6]]
     zmin, zmax = zip(*zlay)
     
     vol_obj = VolumeParams(x_span=xlay, z_spans=zlay, 
         pixels_tot=1, pixels_x=2, pixels_y=3, 
         ref_gray=4, epipolar_band=5, min_correlation=6)
     
     numpy.testing.assert_array_equal(xlay, vol_obj.get_X_lay())
     numpy.testing.assert_array_equal(zmin, vol_obj.get_Zmin_lay())
     numpy.testing.assert_array_equal(zmax, vol_obj.get_Zmax_lay())
     
     self.failUnless(vol_obj.get_cn() == 1)
     self.failUnless(vol_obj.get_cnx() == 2)
     self.failUnless(vol_obj.get_cny() == 3)
     self.failUnless(vol_obj.get_csumg() == 4)
     self.failUnless(vol_obj.get_eps0() == 5)
     self.failUnless(vol_obj.get_corrmin() == 6)
class Test_VolumeParams(unittest.TestCase):
    def setUp(self):
        self.input_volume_par_file_name = "testing_fodder/volume_parameters/volume.par"
        self.temp_output_directory = "testing_fodder/volume_parameters/testing_output"
        
        # create a temporary output directory (will be deleted by the end of test)
        if not os.path.exists(self.temp_output_directory):
            os.makedirs(self.temp_output_directory)
            
        # create an instance of VolumeParams class
        self.vol_obj = VolumeParams()
        
    def test_read_volume(self):
        # Fill the VolumeParams object with parameters from test file
        self.vol_obj.read_volume_par(self.input_volume_par_file_name)
        
        # check that all parameters are equal to the contents of test file
        numpy.testing.assert_array_equal(numpy.array([111.111, 222.222]), self.vol_obj.get_X_lay())
        numpy.testing.assert_array_equal(numpy.array([333.333, 444.444]), self.vol_obj.get_Zmin_lay())
        numpy.testing.assert_array_equal(numpy.array([555.555, 666.666]), self.vol_obj.get_Zmax_lay())
         
        self.failUnless(self.vol_obj.get_cnx() == 777.777)
        self.failUnless(self.vol_obj.get_cny() == 888.888)
        self.failUnless(self.vol_obj.get_cn() == 999.999)
        self.failUnless(self.vol_obj.get_csumg() == 1010.1010)
        self.failUnless(self.vol_obj.get_corrmin() == 1111.1111)
        self.failUnless(self.vol_obj.get_eps0() == 1212.1212)
        
    def test_setters(self):
        xlay = numpy.array([111.1, 222.2])
        self.vol_obj.set_X_lay(xlay)
        numpy.testing.assert_array_equal(xlay, self.vol_obj.get_X_lay())
        
        zmin = numpy.array([333.3, 444.4])
        self.vol_obj.set_Zmin_lay(zmin)
        numpy.testing.assert_array_equal(zmin, self.vol_obj.get_Zmin_lay())
        
        zmax = numpy.array([555.5, 666.6])
        self.vol_obj.set_Zmax_lay(zmax)
        numpy.testing.assert_array_equal(zmax, self.vol_obj.get_Zmax_lay())
        
        self.vol_obj.set_cn(1)
        self.failUnless(self.vol_obj.get_cn() == 1)
        
        self.vol_obj.set_cnx(2)
        self.failUnless(self.vol_obj.get_cnx() == 2)
        
        self.vol_obj.set_cny(3)
        self.failUnless(self.vol_obj.get_cny() == 3)
        
        self.vol_obj.set_csumg(4)
        self.failUnless(self.vol_obj.get_csumg() == 4)
        
        self.vol_obj.set_eps0(5)
        self.failUnless(self.vol_obj.get_eps0() == 5)
        
        self.vol_obj.set_corrmin(6)
        self.failUnless(self.vol_obj.get_corrmin() == 6)
    
    def test_init_kwargs(self):
        """Initialize volume parameters with keyword arguments"""
        xlay = numpy.array([111.1, 222.2])
        zlay = [r_[333.3, 555.5], r_[444.4, 666.6]]
        zmin, zmax = zip(*zlay)
        
        vol_obj = VolumeParams(x_span=xlay, z_spans=zlay, 
            pixels_tot=1, pixels_x=2, pixels_y=3, 
            ref_gray=4, epipolar_band=5, min_correlation=6)
        
        numpy.testing.assert_array_equal(xlay, vol_obj.get_X_lay())
        numpy.testing.assert_array_equal(zmin, vol_obj.get_Zmin_lay())
        numpy.testing.assert_array_equal(zmax, vol_obj.get_Zmax_lay())
        
        self.failUnless(vol_obj.get_cn() == 1)
        self.failUnless(vol_obj.get_cnx() == 2)
        self.failUnless(vol_obj.get_cny() == 3)
        self.failUnless(vol_obj.get_csumg() == 4)
        self.failUnless(vol_obj.get_eps0() == 5)
        self.failUnless(vol_obj.get_corrmin() == 6)
        
    # testing __richcmp__ comparison method of VolumeParams class
    def test_rich_compare(self):
        self.vol_obj2 = VolumeParams()
        self.vol_obj2.read_volume_par(self.input_volume_par_file_name)
        self.vol_obj3 = VolumeParams()
        self.vol_obj3.read_volume_par(self.input_volume_par_file_name)
        self.failUnless(self.vol_obj2 == self.vol_obj3)
        self.failIf(self.vol_obj2 != self.vol_obj3)
        
        self.vol_obj2.set_cn(-999)
        self.failUnless(self.vol_obj2 != self.vol_obj3)
        self.failIf(self.vol_obj2 == self.vol_obj3)
        
        with self.assertRaises(TypeError):
            var = (self.vol_obj2 < self.vol_obj3)
    
    def tearDown(self):
        # remove the testing output directory and its files
        shutil.rmtree(self.temp_output_directory)
示例#23
0
def run_batch(new_seq_first, new_seq_last):
    """ this file runs inside exp_path, so the other names are
    prescribed by the OpenPTV type of a folder:
        /parameters
        /img
        /cal
        /res
    """
    # read the number of cameras
    with open('parameters/ptv.par', 'r') as f:
        n_cams = int(f.readline())

    # Control parameters
    cpar = ControlParams(n_cams)
    cpar.read_control_par(b'parameters/ptv.par')

    # Sequence parameters
    spar = SequenceParams(num_cams=n_cams)
    spar.read_sequence_par(b'parameters/sequence.par', n_cams)
    spar.set_first(new_seq_first)
    spar.set_last(new_seq_last)

    # Volume parameters
    vpar = VolumeParams()
    vpar.read_volume_par(b'parameters/criteria.par')

    # Tracking parameters
    track_par = TrackingParams()
    track_par.read_track_par(b'parameters/track.par')

    # Target parameters
    tpar = TargetParams()
    tpar.read(b'parameters/targ_rec.par')

    #

    # Calibration parameters

    cals = []
    for i_cam in range(n_cams):
        cal = Calibration()
        tmp = cpar.get_cal_img_base_name(i_cam)
        cal.from_file(tmp + b'.ori', tmp + b'.addpar')
        cals.append(cal)

    # sequence loop for all frames
    for frame in range(new_seq_first, new_seq_last + 1):
        print("processing frame %d" % frame)

        detections = []
        corrected = []
        for i_cam in range(n_cams):
            imname = spar.get_img_base_name(i_cam) + str(frame)
            img = imread(imname)
            hp = simple_highpass(img, cpar)
            targs = target_recognition(hp, tpar, i_cam, cpar)
            print(targs)

            targs.sort_y()
            detections.append(targs)
            mc = MatchedCoords(targs, cpar, cals[i_cam])
            pos, pnr = mc.as_arrays()
            print(i_cam)
            corrected.append(mc)

        #        if any([len(det) == 0 for det in detections]):
        #            return False

        # Corresp. + positions.
        sorted_pos, sorted_corresp, num_targs = correspondences(
            detections, corrected, cals, vpar, cpar)

        # Save targets only after they've been modified:
        for i_cam in xrange(n_cams):
            detections[i_cam].write(spar.get_img_base_name(i_cam), frame)


        print("Frame " + str(frame) + " had " \
              + repr([s.shape[1] for s in sorted_pos]) + " correspondences.")

        # Distinction between quad/trip irrelevant here.
        sorted_pos = np.concatenate(sorted_pos, axis=1)
        sorted_corresp = np.concatenate(sorted_corresp, axis=1)

        flat = np.array([corrected[i].get_by_pnrs(sorted_corresp[i]) \
                         for i in xrange(len(cals))])
        pos, rcm = point_positions(flat.transpose(1, 0, 2), cpar, cals, vpar)

        if len(cals) < 4:
            print_corresp = -1 * np.ones((4, sorted_corresp.shape[1]))
            print_corresp[:len(cals), :] = sorted_corresp
        else:
            print_corresp = sorted_corresp

        # Save rt_is
        rt_is = open(default_naming['corres'] + '.' + str(frame), 'w')
        rt_is.write(str(pos.shape[0]) + '\n')
        for pix, pt in enumerate(pos):
            pt_args = (pix + 1, ) + tuple(pt) + tuple(print_corresp[:, pix])
            rt_is.write("%4d %9.3f %9.3f %9.3f %4d %4d %4d %4d\n" % pt_args)
        rt_is.close()
    # end of a sequence loop

    tracker = Tracker(cpar, vpar, track_par, spar, cals, default_naming)
    tracker.full_forward()
class Test_Orientation(unittest.TestCase):
    def setUp(self):
        self.input_ori_file_name = b'testing_fodder/calibration/cam1.tif.ori'
        self.input_add_file_name = b'testing_fodder/calibration/cam2.tif.addpar'
        self.control_file_name = b'testing_fodder/control_parameters/control.par'
        self.volume_file_name = b'testing_fodder/corresp/criteria.par'

        self.calibration = Calibration()
        self.calibration.from_file(self.input_ori_file_name,
                                   self.input_add_file_name)
        self.control = ControlParams(4)
        self.control.read_control_par(self.control_file_name)
        self.vpar = VolumeParams()
        self.vpar.read_volume_par(self.volume_file_name)

    def test_match_detection_to_ref(self):
        """Match detection to reference (sortgrid)"""
        xyz_input = np.array([(10, 10, 10), (200, 200, 200), (600, 800, 100),
                              (20, 10, 2000), (30, 30, 30)],
                             dtype=float)
        coords_count = len(xyz_input)

        xy_img_pts_metric = image_coordinates(
            xyz_input, self.calibration, self.control.get_multimedia_params())
        xy_img_pts_pixel = convert_arr_metric_to_pixel(xy_img_pts_metric,
                                                       control=self.control)

        # convert to TargetArray object
        target_array = TargetArray(coords_count)

        for i in range(coords_count):
            target_array[i].set_pnr(i)
            target_array[i].set_pos(
                (xy_img_pts_pixel[i][0], xy_img_pts_pixel[i][1]))

        # create randomized target array
        indices = range(coords_count)
        shuffled_indices = list(range(coords_count))

        while indices == shuffled_indices:
            random.shuffle(shuffled_indices)

        rand_targ_array = TargetArray(coords_count)
        for i in range(coords_count):
            rand_targ_array[shuffled_indices[i]].set_pos(target_array[i].pos())
            rand_targ_array[shuffled_indices[i]].set_pnr(target_array[i].pnr())

        # match detection to reference
        matched_target_array = match_detection_to_ref(cal=self.calibration,
                                                      ref_pts=xyz_input,
                                                      img_pts=rand_targ_array,
                                                      cparam=self.control)

        # assert target array is as before
        for i in range(coords_count):
            if matched_target_array[i].pos() != target_array[i].pos() \
                    or matched_target_array[i].pnr() != target_array[i].pnr():
                self.fail()

        # # pass ref_pts and img_pts with non-equal lengths
        # with self.assertRaises(ValueError):
        #     match_detection_to_ref(cal=self.calibration,
        #                            ref_pts=xyz_input,
        #                            img_pts=TargetArray(coords_count - 1),
        #                            cparam=self.control)

    def test_point_positions(self):
        """Point positions"""
        # prepare MultimediaParams
        mult_params = self.control.get_multimedia_params()

        mult_params.set_n1(1.)
        mult_params.set_layers(np.array([1.]), np.array([1.]))
        mult_params.set_n3(1.)

        # 3d point
        points = np.array([[17, 42, 0], [17, 42, 0]], dtype=float)

        num_cams = 4
        ori_tmpl = 'testing_fodder/calibration/sym_cam{cam_num}.tif.ori'
        add_file = b'testing_fodder/calibration/cam1.tif.addpar'
        calibs = []
        targs_plain = []
        targs_jigged = []

        jigg_amp = 0.5

        # read calibration for each camera from files
        for cam in range(num_cams):
            ori_name = ori_tmpl.format(cam_num=cam + 1).encode()
            new_cal = Calibration()
            new_cal.from_file(ori_file=ori_name, add_file=add_file)
            calibs.append(new_cal)

        for cam_num, cam_cal in enumerate(calibs):
            new_plain_targ = image_coordinates(
                points, cam_cal, self.control.get_multimedia_params())
            targs_plain.append(new_plain_targ)

            if (cam_num % 2) == 0:
                jigged_points = points - np.r_[0, jigg_amp, 0]
            else:
                jigged_points = points + np.r_[0, jigg_amp, 0]

            new_jigged_targs = image_coordinates(
                jigged_points, cam_cal, self.control.get_multimedia_params())
            targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1, 0, 2)
        targs_jigged = np.array(targs_jigged).transpose(1, 0, 2)
        skew_dist_plain = point_positions(targs_plain, self.control, calibs,
                                          self.vpar)
        skew_dist_jigged = point_positions(targs_jigged, self.control, calibs,
                                           self.vpar)

        if np.any(skew_dist_plain[1] > 1e-10):
            self.fail(('skew distance of target#{targ_num} ' \
                + 'is more than allowed').format(
                    targ_num=np.nonzero(skew_dist_plain[1] > 1e-10)[0][0]))

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(skew_dist_jigged[1] > 0.7):
            self.fail(('skew distance of target#{targ_num} ' \
                + 'is more than allowed').format(
                    targ_num=np.nonzero(skew_dist_jigged[1] > 1e-10)[0][0]))
        if np.any(np.linalg.norm(points - skew_dist_jigged[0], axis=1) > 0.1):
            self.fail('Rays converge on wrong position after jigging.')

    def test_single_camera_point_positions(self):
        """Point positions for a single camera case"""

        num_cams = 1
        # prepare MultimediaParams
        cpar_file = b'testing_fodder/single_cam/parameters/ptv.par'
        vpar_file = b'testing_fodder/single_cam/parameters/criteria.par'
        cpar = ControlParams(num_cams)
        cpar.read_control_par(cpar_file)
        mult_params = cpar.get_multimedia_params()

        vpar = VolumeParams()
        vpar.read_volume_par(vpar_file)

        ori_name = b'testing_fodder/single_cam/calibration/cam_1.tif.ori'
        add_name = b'testing_fodder/single_cam/calibration/cam_1.tif.addpar'
        calibs = []

        # read calibration for each camera from files
        new_cal = Calibration()
        new_cal.from_file(ori_file=ori_name, add_file=add_name)
        calibs.append(new_cal)

        # 3d point
        points = np.array([[1, 1, 0], [-1, -1, 0]], dtype=float)

        targs_plain = []
        targs_jigged = []

        jigg_amp = 0.4

        new_plain_targ = image_coordinates(points, calibs[0], mult_params)
        targs_plain.append(new_plain_targ)

        jigged_points = points - np.r_[0, jigg_amp, 0]

        new_jigged_targs = image_coordinates(jigged_points, calibs[0],
                                             mult_params)
        targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1, 0, 2)
        targs_jigged = np.array(targs_jigged).transpose(1, 0, 2)
        skew_dist_plain = point_positions(targs_plain, cpar, calibs, vpar)
        skew_dist_jigged = point_positions(targs_jigged, cpar, calibs, vpar)

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(
                np.linalg.norm(jigged_points -
                               skew_dist_jigged[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position after jigging.')

    def test_dumbbell(self):
        # prepare MultimediaParams
        mult_params = self.control.get_multimedia_params()
        mult_params.set_n1(1.)
        mult_params.set_layers(np.array([1.]), np.array([1.]))
        mult_params.set_n3(1.)

        # 3d point
        points = np.array([[17.5, 42, 0], [-17.5, 42, 0]], dtype=float)

        num_cams = 4
        ori_tmpl = 'testing_fodder/dumbbell/cam{cam_num}.tif.ori'
        add_file = 'testing_fodder/calibration/cam1.tif.addpar'
        calibs = []
        targs_plain = []

        # read calibration for each camera from files
        for cam in range(num_cams):
            ori_name = ori_tmpl.format(cam_num=cam + 1)
            new_cal = Calibration()
            new_cal.from_file(ori_file=ori_name.encode(),
                              add_file=add_file.encode())
            calibs.append(new_cal)

        for cam_cal in calibs:
            new_plain_targ = flat_image_coordinates(
                points, cam_cal, self.control.get_multimedia_params())
            targs_plain.append(new_plain_targ)

        targs_plain = np.array(targs_plain).transpose(1, 0, 2)

        # The cameras are not actually fully calibrated, so the result is not
        # an exact 0. The test is that changing the expected distance changes
        # the measure.
        tf = dumbbell_target_func(targs_plain, self.control, calibs, 35., 0.)
        self.assertAlmostEqual(tf, 7.14860, 5)  # just a regression test

        # As we check the db length, the measure increases...
        tf_len = dumbbell_target_func(targs_plain, self.control, calibs, 35.,
                                      1.)
        self.assertTrue(tf_len > tf)

        # ...but not as much as when giving the wrong length.
        tf_too_long = dumbbell_target_func(targs_plain, self.control, calibs,
                                           25., 1.)
        self.assertTrue(tf_too_long > tf_len > tf)
示例#25
0
class Test_Orientation(unittest.TestCase):
    def setUp(self):
        self.input_ori_file_name = b'testing_fodder/calibration/cam1.tif.ori'
        self.input_add_file_name = b'testing_fodder/calibration/cam2.tif.addpar'
        self.control_file_name = b'testing_fodder/control_parameters/control.par'
        self.volume_file_name = b'testing_fodder/corresp/criteria.par'

        self.calibration = Calibration()
        self.calibration.from_file(
            self.input_ori_file_name, self.input_add_file_name)
        self.control = ControlParams(4)
        self.control.read_control_par(self.control_file_name)
        self.vpar = VolumeParams()
        self.vpar.read_volume_par(self.volume_file_name)

    def test_match_detection_to_ref(self):
        """Match detection to reference (sortgrid)"""
        xyz_input = np.array([(10, 10, 10),
                              (200, 200, 200),
                              (600, 800, 100),
                              (20, 10, 2000),
                              (30, 30, 30)], dtype=float)
        coords_count = len(xyz_input)

        xy_img_pts_metric = image_coordinates(
            xyz_input, self.calibration, self.control.get_multimedia_params())
        xy_img_pts_pixel = convert_arr_metric_to_pixel(
            xy_img_pts_metric, control=self.control)

        # convert to TargetArray object
        target_array = TargetArray(coords_count)

        for i in range(coords_count):
            target_array[i].set_pnr(i)
            target_array[i].set_pos(
                (xy_img_pts_pixel[i][0], xy_img_pts_pixel[i][1]))

        # create randomized target array
        indices = range(coords_count)
        shuffled_indices = list(range(coords_count))

        while indices == shuffled_indices:
            random.shuffle(shuffled_indices)

        rand_targ_array = TargetArray(coords_count)
        for i in range(coords_count):
            rand_targ_array[shuffled_indices[i]].set_pos(target_array[i].pos())
            rand_targ_array[shuffled_indices[i]].set_pnr(target_array[i].pnr())

        # match detection to reference
        matched_target_array = match_detection_to_ref(cal=self.calibration,
                                                      ref_pts=xyz_input,
                                                      img_pts=rand_targ_array,
                                                      cparam=self.control)

        # assert target array is as before
        for i in range(coords_count):
            if matched_target_array[i].pos() != target_array[i].pos() \
                    or matched_target_array[i].pnr() != target_array[i].pnr():
                self.fail()

        # # pass ref_pts and img_pts with non-equal lengths
        # with self.assertRaises(ValueError):
        #     match_detection_to_ref(cal=self.calibration,
        #                            ref_pts=xyz_input,
        #                            img_pts=TargetArray(coords_count - 1),
        #                            cparam=self.control)

    def test_point_positions(self):
        """Point positions"""
        # prepare MultimediaParams
        mult_params = self.control.get_multimedia_params()

        mult_params.set_n1(1.)
        mult_params.set_layers(np.array([1.]), np.array([1.]))
        mult_params.set_n3(1.)

        # 3d point
        points = np.array([[17, 42, 0],
                           [17, 42, 0]], dtype=float)
        
        num_cams = 4
        ori_tmpl = 'testing_fodder/calibration/sym_cam{cam_num}.tif.ori'
        add_file = b'testing_fodder/calibration/cam1.tif.addpar'
        calibs = []
        targs_plain = []
        targs_jigged = []

        jigg_amp = 0.5

        # read calibration for each camera from files
        for cam in range(num_cams):
            ori_name = ori_tmpl.format(cam_num=cam + 1).encode()
            new_cal = Calibration()
            new_cal.from_file(ori_file=ori_name, add_file=add_file)
            calibs.append(new_cal)

        for cam_num, cam_cal in enumerate(calibs):
            new_plain_targ = image_coordinates(
                points, cam_cal, self.control.get_multimedia_params())
            targs_plain.append(new_plain_targ)
            
            if (cam_num % 2) == 0:
                jigged_points = points - np.r_[0, jigg_amp, 0]
            else:
                jigged_points = points + np.r_[0, jigg_amp, 0]

            new_jigged_targs = image_coordinates(
                jigged_points, cam_cal, self.control.get_multimedia_params())
            targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1,0,2)
        targs_jigged = np.array(targs_jigged).transpose(1,0,2)
        skew_dist_plain = point_positions(targs_plain, self.control, calibs, self.vpar)
        skew_dist_jigged = point_positions(targs_jigged, self.control, calibs, self.vpar)

        if np.any(skew_dist_plain[1] > 1e-10):
            self.fail(('skew distance of target#{targ_num} ' \
                + 'is more than allowed').format(
                    targ_num=np.nonzero(skew_dist_plain[1] > 1e-10)[0][0]))

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(skew_dist_jigged[1] > 0.7):
            self.fail(('skew distance of target#{targ_num} ' \
                + 'is more than allowed').format(
                    targ_num=np.nonzero(skew_dist_jigged[1] > 1e-10)[0][0]))
        if np.any(np.linalg.norm(points - skew_dist_jigged[0], axis=1) > 0.1):
            self.fail('Rays converge on wrong position after jigging.')

    def test_single_camera_point_positions(self):
        """Point positions for a single camera case"""

        num_cams = 1
        # prepare MultimediaParams
        cpar_file = b'testing_fodder/single_cam/parameters/ptv.par'
        vpar_file = b'testing_fodder/single_cam/parameters/criteria.par'
        cpar = ControlParams(num_cams)
        cpar.read_control_par(cpar_file)
        mult_params = cpar.get_multimedia_params()

        vpar = VolumeParams()
        vpar.read_volume_par(vpar_file)

        ori_name = b'testing_fodder/single_cam/calibration/cam_1.tif.ori'
        add_name = b'testing_fodder/single_cam/calibration/cam_1.tif.addpar'
        calibs = []


        # read calibration for each camera from files
        new_cal = Calibration()
        new_cal.from_file(ori_file=ori_name, add_file=add_name)
        calibs.append(new_cal)


        # 3d point
        points = np.array([[1, 1, 0],
                           [-1, -1, 0]], dtype=float)

        targs_plain = []
        targs_jigged = []


        jigg_amp = 0.4


        new_plain_targ = image_coordinates(
            points, calibs[0], mult_params)
        targs_plain.append(new_plain_targ)

        jigged_points = points - np.r_[0, jigg_amp, 0]

        new_jigged_targs = image_coordinates(
            jigged_points, calibs[0], mult_params)
        targs_jigged.append(new_jigged_targs)

        targs_plain = np.array(targs_plain).transpose(1,0,2)
        targs_jigged = np.array(targs_jigged).transpose(1,0,2)
        skew_dist_plain = point_positions(targs_plain, cpar, calibs, vpar)
        skew_dist_jigged = point_positions(targs_jigged, cpar, calibs, vpar)

        if np.any(np.linalg.norm(points - skew_dist_plain[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position.')

        if np.any(np.linalg.norm(jigged_points - skew_dist_jigged[0], axis=1) > 1e-6):
            self.fail('Rays converge on wrong position after jigging.')
    
    def test_dumbbell(self):
        # prepare MultimediaParams
        mult_params = self.control.get_multimedia_params()
        mult_params.set_n1(1.)
        mult_params.set_layers(np.array([1.]), np.array([1.]))
        mult_params.set_n3(1.)

        # 3d point
        points = np.array([[17.5, 42, 0],
                           [-17.5, 42, 0]], dtype=float)
        
        num_cams = 4
        ori_tmpl = 'testing_fodder/dumbbell/cam{cam_num}.tif.ori'
        add_file = 'testing_fodder/calibration/cam1.tif.addpar'
        calibs = []
        targs_plain = []

        # read calibration for each camera from files
        for cam in range(num_cams):
            ori_name = ori_tmpl.format(cam_num=cam + 1)
            new_cal = Calibration()
            new_cal.from_file(ori_file=ori_name.encode(), add_file=add_file.encode())
            calibs.append(new_cal)

        for cam_cal in calibs:
            new_plain_targ = flat_image_coordinates(
                points, cam_cal, self.control.get_multimedia_params())
            targs_plain.append(new_plain_targ)

        targs_plain = np.array(targs_plain).transpose(1,0,2)
        
        # The cameras are not actually fully calibrated, so the result is not 
        # an exact 0. The test is that changing the expected distance changes 
        # the measure.
        tf = dumbbell_target_func(targs_plain, self.control, calibs, 35., 0.)
        self.assertAlmostEqual(tf, 7.14860, 5) # just a regression test
        
        # As we check the db length, the measure increases...
        tf_len = dumbbell_target_func(
            targs_plain, self.control, calibs, 35., 1.)
        self.assertTrue(tf_len > tf)
        
        # ...but not as much as when giving the wrong length.
        tf_too_long = dumbbell_target_func(
            targs_plain, self.control, calibs, 25., 1.)
        self.assertTrue(tf_too_long > tf_len > tf)