Exemplo n.º 1
0
    def test_load_calibrations_csv():
        """
        Test load_calibrations parsing CSV.

        WARNING
            Call `test_load_calibrations_str` before
            `test_load_calibrations_dict` and before
            `test_compute_calibrations`so that the dict can be loaded
            rather than manually inputted.

        CSV FORMAT
            - delimiter: ', '
            - no floats, round and convert to int using known precision
            - strings in double quotes

            e.g. "varname", var[0], var[1], ...\\n
        """
        testcalibpath = calibsdir + '/camera_params.csv'
        if not os_exists(testcalibpath):
            raise RuntimeError('Can\'t find \'%s\'' % testcalibpath)
        global cpdict  # global for use in other functions
        cpdict = {}

        # Load params from test
        with open(testcalibpath, 'r') as f:
            lines = f.read().splitlines()
        entries = [line.split(', ') for line in lines]
        for c in entries:
            name = c[0].replace('\"', '')
            if name not in ('cameraMatrix', 'distCoeffs', 'w', 'h'):
                warning(
                    'variable name: \'%s\' not valid calib name' % name
                )
                continue
            if name in ('w', 'h'):
                cpdict[name] = int(c[1])
                continue

            shape = [int(v) for v in c[1].replace('\"', '').split('x')]
            data = asarray([int(v) for v in c[2:]]) / 10**4
            if name == 'cameraMatrix':
                cpdict[name] = reshape(data, shape).astype('float64')
            elif name == 'distCoeffs':
                cpdict[name] = reshape(data, shape).astype('float64')
            else:
                raise RuntimeError('Unreachable state!?')

        # Test calib loading
        calib = CalibratePSEye()
        calib.load_calibrations(calibsdir + '/camera_params.csv')
        for k in cpdict.keys():
            if not array_equal(getattr(calib, k), cpdict[k]):
                raise RuntimeError('\'%s\' did not match' % k)
            debug('\'%s\' matched' % k)
Exemplo n.º 2
0
    def test_save_calibrations():
        """
        Test save_calibrations.

        Loading calibs was already tested above, so can rely on it.

        CSV FORMAT
            - delimiter: ', '
            - no floats, round and convert to int using known precision
            - strings in double quotes

            e.g. "varname", var[0], var[1], ...\\n
        """
        fn_cp = calibsdir + '/camera_params.csv'
        if not os_exists(fn_cp):
            raise RuntimeError('tests/camera_params.csv could not be found')
        # set not to tests/ (`load_calibrations` will do that)
        #   don't want to overwrite test data
        calib1 = CalibratePSEye()
        calib1.init_chessboard(p, o)
        try:
            # Load known calibs and then save
            cp = calib1.calibpath
            debug('%s' % calib1.calibpath)
            calib1.load_calibrations(fn_cp)
            calib1.calibpath = cp
            calib1.save_calibrations()
            if not os_exists(calib1.calibpath):
                raise RuntimeError('Failed to create calib path \'%s\''
                                   % calib1.calib_path)
            # Compare saving
            with open(fn_cp, 'r') as f:
                f1 = f.read()
            with open(cp+'/camera_params.csv', 'r') as f:
                f2 = f.read()
            if f1 != f2:
                raise RuntimeError('Camera parameter csvs did not match')

            # Compare loading
            calib2 = CalibratePSEye()
            calib2.load_calibrations(calib1.calibpath+'/camera_params.csv')
            paramlist = ('cameraMatrix', 'distCoeffs')
            for k in paramlist:
                k1 = getattr(calib1, k)
                k2 = getattr(calib2, k)
                if not array_equal(k1, k2):
                    raise RuntimeError(
                        'param \'%s\' does not match between calib1 and calib2' % k
                    )
                debug('\'%s\' matched' % k)
        finally:
            calib1.removepath()
Exemplo n.º 3
0
 def test_load_calibrations_asserts():
     """
     Test load calibrations assertions. This is separate from loading with
     str or dict input to avoid duplicate code and unclear asymmetry
     """
     calib = CalibratePSEye()
     for t in (int, float, complex, list, tuple, range, dict, set,
               frozenset, bool, bytes, bytearray, memoryview):
         try:
             calib.load_calibrations(t)
         except TypeError:
             debug('Caught \'%s\' calibrations' % t.__name__)
         else:
             raise RuntimeError('Failed to catch %s calibrations' % t.__name__)
Exemplo n.º 4
0
    def test_load_calibrations_dict():
        """
        Test the loading of a dict of calibration matrices

        CSV FORMAT
            - delimiter: ', '
            - no floats, round and convert to int using known precision
            - strings in double quotes

            e.g. "varname", var[0], var[1], ...\\n
        """
        # raise NotImplementedError
        global cpdict
        calib = CalibratePSEye()
        calib.load_calibrations(cpdict)
        for k in cpdict.keys():
            if not array_equal(getattr(calib, k), cpdict[k]):
                raise RuntimeError('\'%s\' did not match' % k)
            debug('\'%s\' matched' % k)
Exemplo n.º 5
0
    def test_internal_correct_and_save():
        """
        Test internal correction saving method.
        """
        calib = CalibratePSEye()
        fn_c = calibsdir + '/camera_params.csv'
        # Asserts
        for t in (int, float, complex, list, tuple, range, dict, set,
                  frozenset, bool, bytes, bytearray, memoryview):
                try:
                    calib.correct_and_save(t)
                except TypeError:
                    pass
                else:
                    raise RuntimeError('Failed to catch %s imgpath' % t.__name__)
        calib.load_calibrations(fn_c)
        cp = calib.calibpath
        calib.calibpath = None
        try:
            calib.correct_and_save('file-that-does-not-exist')
        except RuntimeError:
            pass
        else:
            raise RuntimeError('Failed to catch _calib_path is None')

        # Saving
        calib.calibpath = cp
        imgpath = testdir + '/raw'
        storeddir = testdir + '/00000000-000000_undistorted'
        storedcp = testdir + '/00000000-000000_camera_params.csv'
        if os_exists(storeddir):
            rmtree(storeddir)
        if os_exists(storedcp):
            os_remove(storedcp)
        ud1 = calib.correct_and_save(imgpath)
        try:
            # Proper saving
            if not os_exists(storeddir) or not os_exists(storedcp):
                raise RuntimeError('Error creating corrected directories')
            imgcount1 = len([f for f in listdir(imgpath) if f[-4:].lower() == '.jpg'])
            imgcount2 = len([f for f in listdir(storeddir) if f[-4:].lower() == '.jpg'])
            if imgcount1 != imgcount2:
                raise RuntimeError('Not all images were saved')

            # Correct calibration
            #   Check pre-save equality
            imglist = [f for f in listdir(imgpath) if f[-4:].lower() == '.jpg']
            rawimg = [cv_imread(imgpath + '/' + f) for f in imglist]
            ud2 = calib.correct(rawimg)  # will know if `correct` works
            if not array_equal(ud1, ud2):
                raise RuntimeError('Failed pre-save equality check')

            #   Check post-save equality
            for i in range(len(imglist)):
                fnud = storeddir + ('/_f%s' % str(i+1).zfill(5)) + '.jpg'
                cv_imwrite(fnud, ud2[i,...], (IMWRITE_JPEG_QUALITY, 100))
            ud1list = [cv_imread(storeddir + '/' + f) for f in imglist]
            ud2list = [cv_imread(storeddir + '/_' + f) for f in imglist]

            ud1reload = asarray(ud1list, dtype='uint8')
            ud2reload = asarray(ud2list, dtype='uint8')
            if not array_equal(ud1reload, ud2reload):
                raise RuntimeError('Failed reload equality check')
        finally:
            os_remove(storedcp)
            rmtree(storeddir)
            try:
                if os_exists(storedcp):
                    raise RuntimeError('failed to deleted cameraParams csv')
                if os_exists(storeddir):
                    raise RuntimeError('failed to remove undistored img dir')
            except AssertionError:
                raise RuntimeError('Exception during test cleanup')
Exemplo n.º 6
0
    def test_internal_correct():
        """
        Test internal correction method.

        Discovered this song while debugging this test case on 2020-06-19
        https://open.spotify.com/track/5XgYWQKEqSqA5vXJmwZa6n?si=HvcZD32-T2KRspTPcb4uGQ
        """
        calib = CalibratePSEye()
        calib.load_calibrations(calibsdir + '/camera_params.csv')

        # test datatype check
        try:
            for t in ('uint16', 'uint32', 'uint64', 'int16', 'int32', 'int64',
                      'float32', 'float64', 'object'):
                frames = zeros((240, 320, 3), dtype=t)
                calib.correct(frames)
        except TypeError:
            pass
        else:
            raise RuntimeError('Failed to catch not-uint8 dtype')

        # test size check
        try:
            frames = zeros((240,320), dtype='uint8')
            calib.correct(frames)
        except TypeError:
            pass
        else:
            raise RuntimeError('Failed to catch frames too few dimensions')
        try:
            frames = zeros((240,320,1,1,1), dtype='uint8')
            calib.correct(frames)
        except TypeError:
            pass
        else:
            raise RuntimeError('Failed to catch frames too many dimensions')

        # setup test
        frames = []
        for f in listdir(testdir+'/raw'):
            if f[-4:].lower() == '.jpg':
                frames.append(cv_imread(testdir + '/raw/' + f))
        fshape = [len(frames)] + list(frames[0].shape)
        u1 = zeros(fshape, dtype='uint8')
        for i in range(len(frames)):
            f = frames[i].copy()
            u1[i,...] = undistort(f, calib.cameraMatrix, calib.distCoeffs, None)

        # test single frame
        u2 = calib.correct(frames[0])
        if not array_equal(u1[0,...], u2):
            raise RuntimeError('Single-frame undistort/remap is incorrect')

        # test several frames
        u2 = calib.correct(asarray(frames, dtype='uint8'))
        if not array_equal(u1, u2):
            raise RuntimeError('Multi-frame ndarray undistort/remap is incorrect')

        u2 = calib.correct(frames)
        if not array_equal(u1, u2):
            raise RuntimeError('Multi-frame list undistort/remap is incorrect')