def test_rich_compare(self):
     self.cp_obj2 = ControlParams(4)
     self.cp_obj2.read_control_par(self.input_control_par_file_name)
     
     self.cp_obj3 = ControlParams(4)
     self.cp_obj3.read_control_par(self.input_control_par_file_name)
        
     self.failUnless(self.cp_obj2 == self.cp_obj3)
     self.failIf(self.cp_obj2 != self.cp_obj3)
        
     self.cp_obj2.set_hp_flag(False)
     self.failUnless(self.cp_obj2 != self.cp_obj3)
     self.failIf(self.cp_obj2 == self.cp_obj3)
     
     with self.assertRaises(TypeError):
         var = (self.cp_obj2 > self.cp_obj3)  # unhandled operator > 
 def setUp(self):
     self.input_img = np.array(
         [[0, 0, 0, 0, 0], [0, 255, 255, 255, 0], [0, 255, 255, 255, 0],
          [0, 255, 255, 255, 0], [0, 0, 0, 0, 0]],
         dtype=np.uint8)
     self.filter_hp = 0
     self.control = ControlParams(4)
     self.control.set_image_size((5, 5))
 def setUp(self):
     self.input_control_par_file_name = "testing_fodder/control_parameters/control.par"
     self.temp_output_directory = "testing_fodder/control_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 ControlParams class
     self.cp_obj = ControlParams(4)
Example #4
0
    def setUp(self):
        self.input_ori_file_name = r'testing_fodder/calibration/cam1.tif.ori'
        self.input_add_file_name = r'testing_fodder/calibration/cam2.tif.addpar'
        self.control_file_name = r'testing_fodder/control_parameters/control.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)
Example #5
0
    def setUp(self):
        control_file_name = r'testing_fodder/corresp/control.par'
        self.control = ControlParams(4)
        self.control.read_control_par(control_file_name)

        self.cal = Calibration()
        self.cal.from_file("testing_fodder/calibration/cam1.tif.ori",
                           "testing_fodder/calibration/cam1.tif.addpar")
        self.orig_cal = Calibration()
        self.orig_cal.from_file("testing_fodder/calibration/cam1.tif.ori",
                                "testing_fodder/calibration/cam1.tif.addpar")
    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)
    def test_transforms(self):
        """Transform in well-known setup gives precalculates results."""
        cpar = ControlParams(1)
        cpar.set_image_size((1280, 1000))
        cpar.set_pixel_size((0.1, 0.1))

        metric_pos = np.array([[1., 1.], [-10., 15.], [20., -30.]])
        pixel_pos = np.array([[650., 490.], [540., 350.], [840., 800.]])

        np.testing.assert_array_almost_equal(
            pixel_pos, convert_arr_metric_to_pixel(metric_pos, cpar))
        np.testing.assert_array_almost_equal(
            metric_pos, convert_arr_pixel_to_metric(pixel_pos, cpar))
Example #9
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)
Example #10
0
    def test_one_targets2(self):
        img = np.array(
            [[0, 0, 0, 0, 0], [0, 255, 250, 250, 0], [0, 251, 253, 251, 0],
             [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]],
            dtype=np.uint8)

        cpar = ControlParams(4, image_size=(5, 5))
        tpar = TargetParams(gvthresh=[250, 100, 20, 20],
                            discont=5,
                            pixel_count_bounds=(1, 10),
                            min_sum_grey=12,
                            xsize_bounds=(1, 10),
                            ysize_bounds=(1, 10))

        targs = target_recognition(img, tpar, 0, cpar)
        self.assertEqual(len(targs), 1)
        self.assertEqual(targs[0].count_pixels(), (4, 3, 2))
 def test_instantiate_fast(self):
     """ControlParams instantiation through constructor"""
     cp = ControlParams(4, ['headers', 'hp', 'allcam'], (1280, 1024), 
         (15.15,16.16), 18, [19.19], [21.21], 20.20)
     
     self.failUnless(cp.get_num_cams() == 4)
     self.failUnless(cp.get_hp_flag())
     self.failUnless(cp.get_allCam_flag())
     self.failUnless(cp.get_tiff_flag())
     self.failUnless(cp.get_image_size(), (1280, 1024))
     self.failUnless(cp.get_pixel_size() == (15.15,16.16))
     self.failUnless(cp.get_chfield() == 0)
     
     mm = cp.get_multimedia_params()
     self.failUnless(mm.get_n1() == 18)
     self.failUnless(mm.get_n2()[0] == 19.19)
     self.failUnless(mm.get_n3() == 20.20)
     self.failUnless(mm.get_d()[0] == 21.21)
Example #12
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)
Example #13
0
    def test_instantiate(self):
        """Creating a MatchedCoords object"""
        cal = Calibration()
        cpar = ControlParams(4)

        cal.from_file("testing_fodder/calibration/cam1.tif.ori",
                      "testing_fodder/calibration/cam2.tif.addpar")
        cpar.read_control_par("testing_fodder/corresp/control.par")
        targs = read_targets("testing_fodder/frame/cam1.", 333)

        mc = MatchedCoords(targs, cpar, cal)
        pos, pnr = mc.as_arrays()

        # x sorted?
        self.failUnless(np.all(pos[1:, 0] > pos[:-1, 0]))

        # Manually verified order for the loaded data:
        np.testing.assert_array_equal(
            pnr, np.r_[6, 11, 10, 8, 1, 4, 7, 0, 2, 9, 5, 3, 12])
Example #14
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)
    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))
Example #16
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)
Example #17
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)
Example #18
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
Example #19
0
    def test_two_targets(self):
        img = np.array([[0, 0, 0, 0, 0], [0, 255, 0, 0, 0], [0, 0, 0, 0, 0],
                        [0, 0, 0, 251, 0], [0, 0, 0, 0, 0]],
                       dtype=np.uint8)

        cpar = ControlParams(4, image_size=(5, 5))
        tpar = TargetParams(gvthresh=[250, 100, 20, 20],
                            discont=5,
                            pixel_count_bounds=(1, 10),
                            min_sum_grey=12,
                            xsize_bounds=(1, 10),
                            ysize_bounds=(1, 10))

        targs = target_recognition(img, tpar, 0, cpar)

        self.assertEqual(len(targs), 2)
        self.assertEqual(targs[0].count_pixels(), (1, 1, 1))

        # Exclude the first target and try again:
        tpar.set_grey_thresholds([252, 100, 20, 20])
        targs = target_recognition(img, tpar, 0, cpar)

        self.assertEqual(len(targs), 1)
        self.assertEqual(targs[0].count_pixels(), (1, 1, 1))
Example #20
0
    def setUp(self):
        self.control = ControlParams(4)

        self.calibration = Calibration()
Example #21
0
import numpy as np
from optv.calibration import Calibration
from optv.parameters import ControlParams
from optv.imgcoord import image_coordinates
from optv.transforms import convert_arr_metric_to_pixel

num_cams = 3
num_frames = 5
velocity = 0.01

part_traject = np.zeros((num_frames, 3))
part_traject[:, 0] = np.r_[:num_frames] * velocity

# Find targets on each camera.
cpar = ControlParams(3)
cpar.read_control_par("testing_fodder/track/parameters/control_newpart.par")

targs = []
for cam in xrange(num_cams):
    cal = Calibration()
    cal.from_file("testing_fodder/cal/sym_cam%d.tif.ori" % (cam + 1),
                  "testing_fodder/cal/cam1.tif.addpar")
    targs.append(
        convert_arr_metric_to_pixel(
            image_coordinates(part_traject, cal, cpar.get_multimedia_params()),
            cpar))

for frame in xrange(num_frames):
    # write 3D positions:
    with open("testing_fodder/track/res_orig/particles.%d" % (frame + 1),
Example #22
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()