コード例 #1
0
def main(args):
    for filename in args.input:
        try:
            if filename == '-':
                print('*** (stdin) ***')
                print_metadata(c3d.Reader(sys.stdin))
            else:
                print('*** {} ***'.format(filename))
                with open(filename, 'rb') as handle:
                    print_metadata(c3d.Reader(handle))
        except Exception as err:
            print(err)
コード例 #2
0
    def test_c_sgi(self):
        ''' Compare identical SGI/MIPS files encoded using both floating-point and integer representations.
        '''

        FMT_SGI_INT = c3d.Reader(Zipload._get(self.ZIP, self.MIPS_INT))
        FMT_SGI_REAL = c3d.Reader(Zipload._get(self.ZIP, self.MIPS_REAL))

        proc_type = 'SGI'
        test_id = '{} format test'.format(proc_type)

        verify.equal_headers(test_id, FMT_SGI_INT, FMT_SGI_REAL, 'INT', 'REAL',
                             False, True)
        verify.data_is_equal(FMT_SGI_INT, FMT_SGI_REAL, 'INT', 'REAL')

        print('SGI FORMAT: OK')
コード例 #3
0
ファイル: test_c3d.py プロジェクト: MattiasFredriksson/py-c3d
    def test_set_params(self):
        r = c3d.Reader(Zipload._get('sample08.zip', 'TESTDPI.c3d'))
        w = c3d.Writer(
            point_rate=r.point_rate,
            analog_rate=r.analog_rate,
            point_scale=r.point_scale,
        )
        w.add_frames([(p, a) for _, p, a in r.read_frames()])

        h = io.BytesIO()
        w.set_start_frame(255)
        w.set_point_labels(r.point_labels)
        w.set_analog_labels(r.analog_labels)
        w.set_analog_general_scale(r.get('ANALOG:GEN_SCALE').float_value)

        # Screen axis
        X, Y = '-Y', '+Z'
        w.set_screen_axis()
        w.set_screen_axis(X, Y)
        X_v, Y_v = w.get_screen_xy_strings()
        assert X_v == X and Y == Y_v, 'Mismatch between set & get screen axis.'
        assert np.all(np.equal(r.point_labels,
                               w.point_labels)), 'Expected labels to be equal.'

        test_name = 'TEST_PARAM'
        test_string = 'lorem ipsum'
        w.point_group.add_str(test_name, 'void descriptor', test_string)

        assert w.point_group.get(test_name).total_bytes == len(test_string), \
               "Mismatch in number of bytes encoded by 'Group.add_str'"

        w.write(h)
コード例 #4
0
ファイル: pycgmIO.py プロジェクト: kirstenEhlers/pyCGM
def loadC3D(filename):

    if useEZC3D == True:
        print("Using EZC3D")
        return loadEZC3D(filename)

    reader = c3d.Reader(open(filename, 'rb'))

    labels = reader.get('POINT:LABELS').string_array
    mydict = {}
    mydictunlabeled = {}
    data = []
    dataunlabeled = []
    prog_val = 1
    counter = 0
    data_length = reader.last_frame() - reader.first_frame()
    markers = [str(label.rstrip()) for label in labels]

    for frame_no, points, analog in reader.read_frames(True, True):
        for label, point in zip(markers, points):
            #Create a dictionary with format LFHDX: 123
            if label[0] == '*':
                if point[0] != np.nan:
                    mydictunlabeled[label] = point
            else:
                mydict[label] = point

        data.append(mydict)
        dataunlabeled.append(mydictunlabeled)
        mydict = {}
    return [data, dataunlabeled, markers]
コード例 #5
0
def parse_motion(c3d_data, mmm_data, downsample_factor, marker_set):
    # Open files.
    c3d_reader = c3d.Reader(StringIO.StringIO(c3d_data))
    xml_root = et.fromstring(mmm_data)

    # Extract root position at first frame from MMM file.
    xml_pos = xml_root.find('./Motion/MotionFrames/MotionFrame/RootPosition')
    xml_rot = xml_root.find('./Motion/MotionFrames/MotionFrame/RootRotation')
    assert xml_pos is not None
    assert xml_rot is not None
    pose_pos = [float(x) for x in xml_pos.text.split(' ')]
    pose_rot = [float(x) for x in xml_rot.text.split(' ')]

    xml_timesteps = xml_root.findall(
        './Motion/MotionFrames/MotionFrame/Timestep')
    if len(xml_timesteps) < 2:
        return None, None, None
    step0 = float(xml_timesteps[0].text)
    step1 = float(xml_timesteps[1].text)
    fps = np.round(1. / (step1 - step0))
    if fps / downsample_factor <= 40.:
        # Do not downsample motions that would then be less than 40 FPS
        downsample_factor = 1.
    interval = int((step1 - step0) * 1000. * float(downsample_factor))  # in ms

    # Extract marker names (some markers are named <Prefix>:<MarkerName>) and filter those to only include
    # the ones that we support across all motions.
    marker_names = [
        marker.rstrip().split(':')[-1] for marker in c3d_reader.point_labels
    ]
    supported_indexes = [
        idx for idx, name in enumerate(marker_names)
        if name in SUPPORTED_MARKER_NAMES[marker_set]
    ]
    markers = [marker_names[idx] for idx in supported_indexes]

    # Extract Cartesian coordinates from C3D file and downsample.
    frames = []
    for idx, points, _ in c3d_reader.read_frames():
        xyz_coordinates = points[supported_indexes, 0:3]
        frame = xyz_coordinates.flatten()
        frames.append(frame)
    frames = np.array(frames)[::downsample_factor, :]

    # Normalize all frames, that is rotate and translate as well as scale.
    n_markers = len(markers)
    n_frames = len(frames)
    pose_inv = np.linalg.inv(
        pose_matrix(
            [pose_pos[0], pose_pos[1], 0.],  # keep z components as-is
            [0., 0., pose_rot[2]]))  # only rotate around z-axis
    for i in xrange(n_markers):
        start_idx = i * 3
        pos = np.hstack(
            [frames[:, start_idx:start_idx + 3],
             np.ones((n_frames, 1))])
        frames[:, start_idx:start_idx + 3] = np.dot(pose_inv, pos.T).T[:, 0:3]
    frames /= 100.  # convert from cm to m

    return markers, frames, interval
コード例 #6
0
def getEMGFeature(File):
    r = c3d.Reader(open(File, 'rb'))
    EMGFeatures = list()
    EMGData = dict()
    frame_no = 1
    for _, _, analog in r.read_frames():
        for i in range(13, 29):
            if frame_no == 1:
                EMGData[i - 12] = list()
            EMGData[i - 12] += list(analog[i])
        frame_no += 1
    N = len(EMGData[1])
    for i in range(1, len(EMGData) + 1):
        EMGData[i] = np.array(EMGData[i])
    # 1. MAV, Mean Absolute Value of EMG Signal for 16 channels (Time based on the frame 0.008 sec)
    for i in range(len(EMGData)):
        EMGFeatures += [ np.sum(np.absolute(EMGData[1 + i])) / N ]
        
    # 2. Mean Absolute Value Slope (MAVS)
    # Same idea with the velocity, 10 bins, and each bin have 16 channels
    EMGDataBins = np.zeros(10 * len(EMGData))
    for i in range(len(EMGData)):
        bins = [x for x in np.array_split(EMGData[i+1], 10) if len(x) > 0] 
        EMGDataBins[i * len(bins)] = np.absolute(np.sum(bins[0])) / len(bins[0])
        for j in range(1, len(bins)):
            EMGDataBins[i * len(bins) + j] = np.absolute(np.sum(bins[j])) / len(bins[j])
            EMGDataBins[i * len(bins) + j] -= EMGDataBins[i * len(bins) + j - 1]
    EMGFeatures += list(EMGDataBins)
    
    # 3. Variance of EMG (VAR)
    for i in range(len(EMGData)):
        EMGFeatures += [ np.var(EMGData[i+1]) ]
    
    return EMGFeatures
コード例 #7
0
    def test_Manager_renumber_group(self):
        '''Test if renaming (renumbering) groups acts as intended.'''
        reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
        writer = reader.to_writer()
        ref = GroupSample(writer)
        grp_ids = [k for (k, g) in ref.group_listed]

        max_key = ref.max_key

        for i, key in enumerate(grp_ids):
            test_num = max_key + i + 1

            grp = writer.get(key)
            writer.rename_group(key, test_num)
            grp2 = writer.get(test_num)

            assert grp2 is not None, "Rename failed, group with name '%s' does not exist."
            assert grp == grp2, 'Rename failed, group acquired from new name is not identical.'

        ref.assert_entry_count()
        ref.assert_group_items()

        try:
            writer.rename_group(max_key + 1, max_key + 2)
            raise RuntimeError(
                'Overwriting existing numerical ID should raise a KeyError.')
        except ValueError as e:
            pass  # Correct
コード例 #8
0
ファイル: c3d2csv.py プロジェクト: nghorbani/py-c3d
def convert(filename, args, sep, end):
    input = sys.stdin
    output = sys.stdout
    open_file_streams = filename != '-'
    if open_file_streams:
        input = open(filename, 'rb')
        output = open(filename.replace('.c3d', '.csv'), 'w')
    try:
        for frame_no, points, analog in c3d.Reader(input).read_frames(
                copy=False):
            fields = [frame_no]
            for x, y, z, err, cam in points:
                fields.append(str(x))
                fields.append(str(y))
                fields.append(str(z))
                if args.include_error:
                    fields.append(str(err))
                if args.include_camera:
                    fields.append(str(cam))
            if args.include_analog:
                fields.extend(str(x) for x in analog.flatten())
            print(*fields, sep=sep, end=end, file=output)
    finally:
        if open_file_streams:
            input.close()
            output.close()
コード例 #9
0
 def test_Manager_group_listed(self):
     '''Test Manager.group_listed'''
     reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
     grp_list = [k for (k, g) in reader.listed()]
     assert len(
         grp_list
     ) > 0, 'No group items in file or Manager.group_listed  failed'
コード例 #10
0
    def test_Manager_rename_group(self):
        '''Test if renaming groups acts as intended.'''
        reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
        writer = reader.to_writer()
        ref = GroupSample(writer)
        grp_keys = [k for (k, g) in ref.group_items]

        new_names = ['TEST_NAME' + str(i) for i in range(len(grp_keys))]

        for key, test_name in zip(grp_keys, new_names):
            grp = writer.get(key)
            writer.rename_group(key, test_name)
            grp2 = writer.get(test_name)

            assert grp2 is not None, "Rename failed, group with name '%s' does not exist."
            assert grp == grp2, 'Rename failed, group acquired from new name is not identical.'

        ref.assert_entry_count()
        ref.assert_group_list()

        try:
            writer.rename_group(new_names[0], new_names[1])
            raise RuntimeError(
                'Overwriting existing numerical ID should raise a KeyError.')
        except ValueError as e:
            pass  # Correct
コード例 #11
0
def read_frames(filename):

    with open(filename, 'rb') as _handle:
        reader = c3d.Reader(_handle)
        tot_frames = reader.last_frame() - reader.first_frame() + 1
        tot_markers = reader.point_used
        fps = int(reader.header.frame_rate)

        # units = reader.get_string('POINT.UNITS')
        # print(units)
        # origin = reader.get('FORCE_PLATFORM.ORIGIN')

        data = np.zeros((tot_frames, tot_markers + 1, 5))
        for frame, (point) in enumerate(reader.read_frames()):
            for marker in range(tot_markers):
                # frame_index, marker_index, x,y,z,_,_
                data[frame, marker, :] = point[1][
                    marker] / 10  # point[0] is frame number
            data[frame, tot_markers, :] = np.zeros(5)

        makrer_list = []
        for marker in enumerate(reader.point_labels):
            makrer_list.append(marker[1].strip())
        makrer_list.append("ORIGIN")
        tot_markers = tot_markers + 1

    return data[:, :, 0:3], makrer_list, fps, tot_frames
コード例 #12
0
 def test_Manager_group_items(self):
     '''Test Manager.group_items'''
     reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
     grp_keys = [k for (k, g) in reader.items()]
     assert len(
         grp_keys
     ) > 0, 'No group items in file or Manager.group_items failed'
コード例 #13
0
ファイル: mocap.py プロジェクト: boyle/2018-measure-stress
def extract_frames(filename):
    total_points = list()
    total_analog = list()
    len_points = None
    rows_analog = None
    cols_analog = None
    with open(filename, 'rb') as handle:
        reader = c3d.Reader(handle)
        for frame_num, points, analog in reader.read_frames(copy=True):
            total_points.append(points)
            [total_analog.append(i) for i in analog.transpose()]

            # if len_points:
            #     assert(len_points == len(points),
            #            'number of points (markers) in a frame changed')
            # else:
            #     len_points = len(points)
            #
            # if rows_analog:
            #     assert(rows_analog == len(analog),
            #            'number of analog (forceplates) in a frame changed')
            # else:
            #     rows_analog = len(analog)
            #
            # if cols_analog:
            #     assert(cols_analog == len(analog[0]),
            #            'number of analog samples (forceplate measurements) in a frame changed')
            # else:
            #     cols_analog = len(analog[0])
        # assert(reader.analog_rate/reader.point_rate == cols_analog,
        #        'relative points vs. analog sample rate does not match data')
    return np.asarray(total_points), np.asarray(total_analog)
コード例 #14
0
ファイル: mocap.py プロジェクト: boyle/2018-measure-stress
def print_frames(filename, n=np.inf):
    with open(filename, 'rb') as handle:
        reader = c3d.Reader(handle)
        for frame_num, points, analog in reader.read_frames(copy=False):
            print('  [n] %s x %s y %s z %s err cam'%(' '*(6), ' '*8, ' '*8, ' '*3))
            for i, (x, y, z, err, cam) in enumerate(points):
                if err > 0:
                    print('[%d.%02dP] %10.4f %10.4f %10.4f %0.1f %3s' % (frame_num, i, x, y, z, err, hex(int(cam))))
                elif err == 0:
                    print('[%d.%02dP] %10.4f %10.4f %10.4f     %3s' % (frame_num, i, x, y, z, hex(int(cam))))
                else:
                    print('[%d.%02dP] <invalid>' % (frame_num, i))
            print(('  [n]' + '%10s'*12) % ('x1', 'y1', 'z1', 'X1', 'Y1', 'Z1',
                                           'x2', 'y2', 'z2', 'X2', 'Y2', 'Z2'))
            for i, data in enumerate(analog.transpose()):
                print('[%d.%02dA]'%(frame_num, i) + ''.join(' %9.2e'%(k) for k in data))
            avg = np.mean(analog,axis=1)
            print('[%d.%2sA]'%(frame_num, '~~') + ''.join(' %9.2e'%(k) for k in avg))
            x1, y1 = calc_cop(avg[0:3], avg[3:6])
            fm1, xd1, yd1 = calc_vec(avg[0:3])
            print('COP1 (%+0.2f, %+0.2f) mm, %0.2f N (%+5.1f°, %+5.1f°) = %0.1f kg (%0.1f lbs)' %
                  (x1, y1, fm1, xd1, yd1, f_kg(fm1), f_lbs(fm1)))
            x2, y2 = calc_cop(avg[6:9], avg[9:12])
            fm2, xd2, yd2 = calc_vec(avg[6:9])
            print('COP2 (%+0.2f, %+0.2f) mm, %0.2f N (%+5.1f°, %+5.1f°) = %0.1f kg (%0.1f lbs)' %
                  (x2, y2, fm2, xd2, yd2, f_kg(fm2), f_lbs(fm2)))
            # combined both force plates to get an overall COP
            x, y = calc_cop(avg[0:3]+avg[6:9], avg[3:6]+avg[9:12])
            fm, xd, yd = calc_vec(avg[0:3]+avg[6:9])
            print('COP (%+0.2f, %+0.2f) mm, %0.2f N (%+5.1f°, %+5.1f°) = %0.1f kg (%0.1f lbs)' %
                  (x, y, fm, xd, yd, f_kg(fm), f_lbs(fm)))
            if frame_num >= n:
                break  # show first frame only
コード例 #15
0
 def test_Group_remove_param(self):
     '''Test if removing groups acts as intended.'''
     reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
     writer = reader.to_writer()
     for g in writer.values():
         ref = ParamSample(g)
         ref.verify_remove_all()
         ref.verify_add_parameter(100)
コード例 #16
0
def read_c3d_file(file_path):
    """Read INTEL format C3D file and return a subsample of marker positions and conditionals.
    Also prints information about the file content.

    :param file_path: Path to C3D file.
    :type file_path: str
    :return: marker data: {'marker_labels': list, 'trajectories': shape(frames, markers, coordinates),
                           'conditionals': shape(frames, conditionals), 'frame_rate': int}
    :rtype: dict
    """
    try:
        with open(file_path, 'rb') as file_handle:
            with warnings.catch_warnings():
                warnings.simplefilter(
                    "ignore"
                )  # ignore UserWarning: missing parameter ANALOG:DESCRIPTIONS/LABELS
                reader = c3d.Reader(file_handle)

            marker_labels = reader.point_labels
            print("Marker Labels:", ",".join(marker_labels))
            first_frame = reader.first_frame()
            last_frame = reader.last_frame()
            print("First Frame:", first_frame, "Last Frame:", last_frame)
            fps = reader.header.frame_rate
            print("FPS:", fps)
            n_frames = last_frame - first_frame + 1
            total_length = n_frames / fps
            print("Clip length in total:", humanize_time(total_length))
            # Extract positions for each frame.
            pos_array = np.empty([n_frames, len(marker_labels), 3])
            pos_array.fill(np.NAN)
            cond_array = np.empty([n_frames, len(marker_labels)])
            cond_array.fill(np.NAN)
            print("Reading frames... ", end="", flush=True)
            for i, points, _ in reader.read_frames():
                # pos_array[frame, marker], e.g. pos_array[:,11] all frames for 12th marker
                # Convert to a mirrored coordinate system.
                pos_array[i - first_frame, :, :] = np.vstack([
                    -1.0 * points[:, 0], -1.0 * points[:, 2],
                    -1.0 * points[:, 1]
                ]).T
                cond_array[i - first_frame, :] = points[:, 3]
                if n_frames is not None and i - first_frame >= n_frames:
                    break
    except OSError:
        print("ERROR: Could not read file.")
        raise
    print("Done.")

    data = {
        'marker_labels': marker_labels,
        'trajectories': pos_array,
        'conditionals': cond_array,
        'frame_rate': fps,
    }
    return data
コード例 #17
0
    def test_edit(self):
        import edit
        path = 'my-looped-motion.c3d'

        with open(path, 'rb') as f:
            reader = c3d.Reader(f)
            assert reader.frame_count == 900, \
                'Expected 900 point frames in edit.py test, was {}'.format(reader.frame_count)
        # Raises 'FileNotFound' if the file was not generated
        os.remove(path)
コード例 #18
0
    def test_a_intel(self):
        ''' Compare identical INTEL files encoded using both floating-point and integer representations.
        '''

        print('----------------------------')
        print(type(self))
        print('----------------------------')

        FMT_INTEL_INT = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_INT))
        FMT_INTEL_REAL = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))

        proc_type = 'INTEL'
        test_id = '{} format test'.format(proc_type)

        verify.equal_headers(test_id, FMT_INTEL_INT, FMT_INTEL_REAL, 'INT',
                             'REAL', False, True)
        verify.data_is_equal(FMT_INTEL_INT, FMT_INTEL_REAL, 'INT', 'REAL')

        print('INTEL FORMAT: OK')
コード例 #19
0
ファイル: __init__.py プロジェクト: eherr/vis_utils
def load_c3d_file(filepath):
    data = dict()
    with open(filepath, "rb") as in_file:
        reader = c3d.Reader(in_file)
        data["labels"] = reader.point_labels
        data["motion_data"] = []
        for frame in reader.read_frames():
            idx, points = frame[0], frame[1]
            data["motion_data"].append(points)
    return data
コード例 #20
0
 def test_Group_readonly_add_param(self):
     '''Test if adding parameter to a readonly group fails.'''
     reader = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
     for g in reader.values():
         try:
             add_dummy_param(g)
             raise RuntimeError(
                 'Adding to readonly should not be possible.')
         except AttributeError:
             pass
コード例 #21
0
    def test_b_encoded_sample_count(self):

        for file, sample_count in zip(self.zip_files, self.sample_count):
            reader = c3d.Reader(Zipload._get(self.ZIP, file))
            self._log(reader)

            # Verify file count
            assert reader.analog_sample_count == sample_count,\
                'Wrong analog sample count read from file {}/{}. Expected {} was {}'.format(
                 self.ZIP, file, sample_count, reader.analog_sample_count)
            print('{} | SAMPLE_COUNT: OK'.format(file))
コード例 #22
0
 def test_paramsd(self):
     r = c3d.Reader(self._get('params.zip', 'TESTDPI.c3d'))
     w = c3d.Writer(
         point_rate=r.point_rate,
         analog_rate=r.analog_rate,
         point_scale=r.point_scale,
         gen_scale=r.get_float('ANALOG:GEN_SCALE'),
     )
     w.add_frames((p, a) for _, p, a in r.read_frames())
     h = io.BytesIO()
     w.write(h)
コード例 #23
0
    def test_write(self):
        import write
        path = 'random-points.c3d'

        with open(path, 'rb') as f:
            reader = c3d.Reader(f)
            assert reader.frame_count == 100, \
                'Expected 30 point frames in write.py test, was {}'.format(reader.frame_count)
            assert reader.point_used == 24, \
                'Expected 5 point samples in write.py test, was {}'.format(reader.point_used)
        # Raises 'FileNotFound' if the file was not generated
        os.remove(path)
コード例 #24
0
def extract(_file):
    header = c3d.Header(_file)
    frame_rate = header.frame_rate

    reader = c3d.Reader(_file)
    frames = []
    for i, points, analog in reader.read_frames():
        tmp = points[points[:, 4] > -1]                 # 쓰레기값(포인트) 제거
        result = tmp[:, :3]                             # x, y, z 좌표만 담는다.
        frames.append(result.tolist())

    return frame_rate, frames
コード例 #25
0
    def test_e_real_formats(self):
        ''' Compare identical files for different processor formats.
            All files are encoded using the floating-point representations.
        '''

        FMT_INTEL_REAL = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_REAL))
        FMT_DEC_REAL = c3d.Reader(Zipload._get(self.ZIP, self.DEC_REAL))
        FMT_SGI_REAL = c3d.Reader(Zipload._get(self.ZIP, self.MIPS_REAL))

        verify.equal_headers('INTEL-DEC INT format test', FMT_INTEL_REAL,
                             FMT_DEC_REAL, 'INTEL', 'DEC', True, True)
        verify.equal_headers('INTEL-SGI INT format test', FMT_INTEL_REAL,
                             FMT_SGI_REAL, 'INTEL', 'SGI', True, True)
        verify.equal_headers('DEC-SGI INT format test', FMT_DEC_REAL,
                             FMT_SGI_REAL, 'DEC', 'SGI', True, True)

        verify.data_is_equal(FMT_INTEL_REAL, FMT_DEC_REAL, 'INTEL', 'DEC')
        verify.data_is_equal(FMT_INTEL_REAL, FMT_SGI_REAL, 'INTEL', 'SGI')
        verify.data_is_equal(FMT_DEC_REAL, FMT_SGI_REAL, 'DEC', 'SGI')

        print('INTEL-DEC-SGI REAL FORMAT COMPARISON: OK')
コード例 #26
0
    def test_d_int_formats(self):
        ''' Compare identical files for different processor formats.
            All files are encoded using the integer representations.
        '''

        FMT_INTEL_INT = c3d.Reader(Zipload._get(self.ZIP, self.INTEL_INT))
        FMT_DEC_INT = c3d.Reader(Zipload._get(self.ZIP, self.DEC_INT))
        FMT_SGI_INT = c3d.Reader(Zipload._get(self.ZIP, self.MIPS_INT))

        verify.equal_headers('INTEL-DEC INT format test', FMT_INTEL_INT,
                             FMT_DEC_INT, 'INTEL', 'DEC', False, False)
        verify.equal_headers('INTEL-SGI INT format test', FMT_INTEL_INT,
                             FMT_SGI_INT, 'INTEL', 'SGI', False, False)
        verify.equal_headers('DEC-SGI INT format test', FMT_DEC_INT,
                             FMT_SGI_INT, 'DEC', 'SGI', False, False)

        verify.data_is_equal(FMT_INTEL_INT, FMT_DEC_INT, 'INTEL', 'DEC')
        verify.data_is_equal(FMT_INTEL_INT, FMT_SGI_INT, 'INTEL', 'SGI')
        verify.data_is_equal(FMT_DEC_INT, FMT_SGI_INT, 'DEC', 'SGI')

        print('INTEL-DEC-SGI INT FORMAT COMPARISON: OK')
コード例 #27
0
def verify_read_write(zip, file_path, proc_type='INTEL', real=True):
    ''' Compare read write ouput to original read file.
    '''
    A = c3d.Reader(Zipload._get(zip, file_path))

    cpy_mode = 'copy'
    if proc_type != 'INTEL':
        cpy_mode = 'shallow_copy'
    writer = A.to_writer(cpy_mode)

    tmp_path = os.path.join(TEMP, 'write_test.c3d')
    with open(tmp_path, 'wb') as handle:
        writer.write(handle)

    aname = 'Original'
    bname = 'WriteRead'
    test_id = '{} write read test'.format(proc_type)

    with open(tmp_path, 'rb') as handle:
        B = c3d.Reader(handle)
        verify.equal_headers(test_id, A, B, aname, bname, real, real)
        verify.data_is_equal(A, B, aname, bname)
コード例 #28
0
ファイル: test_c3d.py プロジェクト: MattiasFredriksson/py-c3d
 def test_frames(self):
     r = c3d.Reader(Zipload._get('sample08.zip', 'TESTDPI.c3d'))
     self._log(r)
     frames = list(r.read_frames())
     assert len(frames) == 450
     frame_no, points, analog = frames[0]
     assert frame_no == 1, frame_no
     expected = (r.point_used, 5)
     assert points.shape == expected, \
         'point shape: got {}, expected {}'.format(points.shape, expected)
     expected = (r.analog_used, r.header.analog_per_frame)
     assert analog.shape == expected, \
         'analog shape: got {}, expected {}'.format(analog.shape, expected)
コード例 #29
0
def convert(file, output):
    assert '.c3d' in file
    assert '.npy' in output

    points = []
    analog = []
    reader = c3d.Reader(open(file, 'rb'))
    for i, p, a in reader.read_frames():
        points.append(p)
        analog.append(a)

    out_path, ext = os.path.splitext(output)
    np.save(out_path + '_' + 'points' + ext, np.array(points))
    np.save(out_path + '_' + 'analog' + ext, np.array(analog))
コード例 #30
0
def getVelocityNormFeature(File, pointLength = None):
    
    length = 80
    if pointLength is not None:
        length = pointLength
    r = c3d.Reader(open(File, 'rb'))
    i = 1
    data = dict()
    for _, points, _ in r.read_frames():
        data[i] = points
        i += 1
    
    velocity = dict()
    
    for i in range(2, len(data)):
        index = 0
        velocity[i - 2] = np.zeros(len(data[i]) * 3)
        for point, prevPoint in zip(data[i], data[i-1]):
            if point[3] != -1 and prevPoint[3] != -1:
                for j in range(3):
                    velocity[i - 2][index] = (point[j] - prevPoint[j]) / (2 * 0.008)
                    index += 1
            else: index += 3
    
    
    v_norm = dict()
    for i in range(len(velocity)):
        v_norm[i] = np.zeros(int(len(velocity[i]) / 3))
        v_index = 0
        for index in range(len(v_norm[i])):
            for j in range(3):
                v_norm[i][index] += velocity[i][v_index] * velocity[i][v_index]
                v_index += 1
        v_norm[i][index] = math.sqrt(v_norm[i][index])
        
    # Only take 10 frames as our features
    per_sample = len(v_norm) // 10

    avg_v_norm = [0] * (10 * int(length))
    for i in range(1, 11):
        idx = (i - 1) * per_sample 
        for j in range(per_sample):
            index = idx + j
            for k in range(len(v_norm[i])):
                avg_v_norm[(i - 1) * length + k] += v_norm[index][k]
        for k in range(len(v_norm[i])):
            avg_v_norm[(i - 1) * length + k] /= per_sample
            
    return avg_v_norm