Skip to content

I/O

io

BVH file I/O — reading and writing .bvh motion capture files.

Public functions:

  • :func:read_bvh_file — parse a .bvh file into a :class:~pybvh.bvh.Bvh
  • :func:write_bvh_file — write a :class:~pybvh.bvh.Bvh to a .bvh file

read_bvh_file(filepath: str | Path, world_up: str = 'auto', warn_on_world_up_disagreement: bool = True, lr_mapping: dict[str, str] | None = None, body_anchor: str | None = None) -> Bvh

Parse a BVH motion capture file and return a Bvh object.

Parameters:

Name Type Description Default
filepath str or Path

Path to the BVH file.

required
world_up str

World vertical axis. "auto" (default) auto-detects from animation data. Pass a signed axis string like "+y" to skip auto-detection and suppress the disagreement warning.

'auto'
warn_on_world_up_disagreement bool

If True (default) and world_up="auto", emit a UserWarning when the rest-pose and first-frame inferences disagree. The returned clip keeps the setting for its lifetime. Load does not spend it. world_up is inferred again when you assign the motion (root_pos, joint_angles or frames). Each of those inferences follows the setting, and so does :attr:Bvh.world_up_inferred. Clips that a :class:Bvh operation derives from this one (slices, copy(), transformed copies, extract_joints, resample) inherit the setting, along with the world up itself. A concatenation a + b follows a, as it does for frame_time. A clip rebuilt from its data (:func:~pybvh.df_to_bvh, :meth:Bvh.from_df) is a new clip, like one read from a file. It starts from the default. The alternative is a one-shot suppression of the load-time inference only. It would warn again on the first motion assignment of a clip that you asked to keep quiet.

True
lr_mapping dict or None

Explicit left/right joint pair mapping ({"arm.L": "arm.R", ...}). If you give one, the name-based auto-detection is skipped for this file. Use it for skeletons whose naming conventions the heuristic cannot parse.

None
body_anchor str or None

The name of the joint the body's measures start from, set on the clip as :attr:Bvh.body_anchor is set, before the world up is guessed. None (default) leaves the anchor to the rule that :attr:Bvh.body_anchor describes. Give it when you know better than the rule, such as on a rig whose chest and hips meet the L/R pairs at the same depth. The clip and every clip derived from it keep it (see :attr:Bvh.body_anchor).

None

Returns:

Name Type Description
bvh Bvh

A Bvh object containing the skeleton hierarchy, root positions, joint angles, and frame time.

Raises:

Type Description
ValueError

If the file is malformed, for example if its Frame Time is missing, zero, negative, NaN or infinite, or if a joint declares other channels than 3 rotation channels, or 3 position + 3 rotation channels (the error names the joint). The root declares 3 position + 3 rotation channels, or none (CHANNELS 0). Also if the file holds several hierarchies (ROOT blocks): a Bvh is one hierarchy, and the error gives their count. Also if body_anchor names no joint, an end site, or more than one joint (the error of :meth:Bvh.index).

Notes

BVH files store joint angles in degrees. pybvh holds them in radians, on :attr:Bvh.joint_angles. This function converts them on read. :func:write_bvh_file converts them back on write.

A root that declares CHANNELS 0 (Blender's exporter writes one, ROOT __0, above an armature with several root bones) is a static root (:meth:~pybvh.bvhnode.BvhRoot.is_static). It stays at its OFFSET with no rotation: :attr:Bvh.root_pos holds its offset in every frame, and its row of :attr:Bvh.joint_angles is zero. :func:write_bvh_file writes it back as CHANNELS 0.

The name of a ROOT or JOINT is the rest of its line, with the whitespace at both ends removed. Inner whitespace is kept as written: JOINT Bip01 L Thigh (a 3ds Max Biped name) reads as "Bip01 L Thigh", and :func:write_bvh_file writes it back the same. A { as the line's last word opens the block and is not part of the name: ROOT Hips { reads as "Hips". The BVH format has no quoting, and other readers differ on such a name: bvh-python keeps the first word only, and Blender's importer joins the words with underscores (Bip01_L_Thigh). So a file with these names can read differently elsewhere. pybvh does not warn about it.

The reader normalizes three things, rather than preserving them verbatim. So a round-trip is lossless in motion, but not byte-for-byte:

  • Frame time is recovered when the file's value is the frame time of a round rate, truncated or rounded by its exporter. Exporters often print Frame Time at 6 decimals: 0.033333 for 30 fps, which is 30.0003 fps. A resample and back then drifts. The reader looks for the rate with the fewest decimals, from 0 to 3, whose frame time gives exactly the file's text when it is rounded or truncated to the decimals that the file prints. When exactly one rate with that many decimals fits, bvh.frame_time is 1 / rate. When several fit, or none with up to 3 decimals, it is the value as read. 0.033333 and 0.033 read as 1 / 30. 0.004166 reads as 1 / 240, and 0.033367 as 1 / 29.97. 0.017 (every whole rate from 56 to 60 fps fits) and 0.008341 (119.88 and 119.89 fps) are kept as read. A 29.97 fps file becomes 1 / 29.97, which is 1.000001e-6 relative from NTSC's exact 1001 / 30000. When you need that value, set bvh.frame_time = 1001 / 30000 after reading. The rule recovers lost digits, not round numbers. So a text of 17 significant digits or more, which names one float exactly, is kept as read: 0.033366700033366700 reads as itself, one float from 1 / 29.97. The text alone cannot tell a short frame time from a truncated one. So :func:write_bvh_file writes all 17 significant digits (its Notes say why). A clip whose frame_time is 0.033 is written 0.033000000000000002, and it reads back as 0.033. None of the other BVH readers surveyed recovers a rate. Those that use the value take the text as printed. One (fairmotion) rounds the rate to a whole number. Where the rule recovers a rate, the printed value differs from pybvh's by less than one unit of its last decimal (0.033333 against 1 / 30). Where the rule keeps the text, the two agree. The rounded rate differs from pybvh's wherever pybvh's is not whole (0.033367 gives 30 fps, 0.017 59 fps). In a file at 6 decimals, it also differs on some whole rates above 720 fps (0.001386 gives 722 fps, where pybvh reads 721).
  • Channels are reordered to position-first, with the position channels in X, Y, Z order, the order of a :attr:Bvh.root_pos row, on the root and on every translating joint (a joint whose CHANNELS line declares 3 position + 3 rotation channels; its values are :attr:Bvh.joint_translations). A file that declares rotations before positions, or Zposition Yposition Xposition, parses correctly, and the node's pos_channels is ('X', 'Y', 'Z'): the declared order is not kept. Position channels interleaved with rotation channels are read as translate first, then rotate. :func:write_bvh_file writes the canonical order, so a write changes such a declaration once, and the output is the same from then on. The rotation channels keep their declared order, which is the node's Euler order.
  • Offsets and motion values are written at 6 decimal places, so re-reading a written file quantizes at ~1e-6 in the file's own units. The frame time is written at 17 significant digits, which reads back as the same float.

Values that pybvh infers or that you set (world_up, lr_mapping, body_anchor) have nowhere to live in the BVH format. They are lost on write. Re-apply them after reading.

write_bvh_file(bvh: Bvh, filepath: str | Path, verbose: bool = False, overwrite: bool = True) -> None

Write a Bvh object to a .bvh file.

Parameters:

Name Type Description Default
bvh Bvh

The motion data to write.

required
filepath str or Path

Destination file path. Must have a .bvh extension.

required
verbose bool

If True, print a one-line confirmation to stdout on success. Default False, so that preprocessing loops that write many files do not flood the terminal by default.

False
overwrite bool

If True (default), replace an existing file at filepath. Pass False to refuse instead: the call then raises FileExistsError. That is worth doing when the destination is hand-authored data rather than a regenerable output.

True

Raises:

Type Description
ValueError

If the file extension is not .bvh, or if bvh.frame_time is 0 (unset). A file must state its frame time, and :func:read_bvh_file refuses Frame Time: 0. Also if the clip's motion arrays disagree on frame count (the setters do not check it); the file is then left as it was.

FileNotFoundError

If the parent directory does not exist.

FileExistsError

If filepath exists and overwrite=False.

Notes

pybvh stores joint angles in radians, but the BVH format requires degrees. This function converts them on write.

Offsets and motion values are written with 6 decimal places. That is the de facto BVH convention (and what most DCC tools emit). So motion data re-read from a written file is quantized at ~1e-6, in the skeleton's length unit and in degrees.

Frame Time is the exception. It is written at 17 significant digits, with trailing zeros kept (f"{frame_time:#.17g}": 0.033333333333333333 for 30 fps, 0.12000000000000000 for 0.12 s). So the file holds the clip's frame time without loss. A truncated frame time compounds across every frame of a resample, but a truncated coordinate does not. The shortest text that reads back as the same float (Python's repr) is not enough, because :func:read_bvh_file takes a Frame Time with few decimals for an exporter's truncated rate. So 0.12 would read back as 1 / 8, and 0.033 as 1 / 30. The reader keeps a text of 17 significant digits as read. So every frame time that this function writes reads back as the same float.

The BVH format carries no place for world_up, lr_mapping, or source_path. Those are lost on write, and re-inferred on read. The root's channels, and a translating joint's, are always written position-first, as Xposition Yposition Zposition, then the rotation channels in the node's Euler order, whatever order the source file declared. So a write reorders a node whose file declared its position channels in another order, after its rotations or interleaved with them (:func:read_bvh_file reads all three).