Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add configuration option ``zero_pad`` for zero padding PNGs. (#1828)

Daniel Adelodun8f9df564257c
diff --git a/manim/_config/default.cfg b/manim/_config/default.cfg
index dfcd97585..d62dc0def 100644
--- a/manim/_config/default.cfg
+++ b/manim/_config/default.cfg
@@ -32,6 +32,9 @@ write_all = False
# -g, --save_pngs
save_pngs = False
+# -0, --zero_pad
+zero_pad = 4
+
# -i, --save_as_gif
save_as_gif = False
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index 7ee1e5c79..b5c193730 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -295,6 +295,7 @@ class ManimConfig(MutableMapping):
"window_monitor",
"write_all",
"write_to_movie",
+ "zero_pad",
}
def __init__(self) -> None:
@@ -438,6 +439,15 @@ class ManimConfig(MutableMapping):
else:
raise ValueError(f"{key} must be {lo} <= {key} <= {hi}")
+ def _set_int_between(self, key: str, val: int, lo: int, hi: int) -> None:
+ """Set ``key`` to ``val`` if lo <= val <= hi."""
+ if lo <= val <= hi:
+ self._d[key] = val
+ else:
+ raise ValueError(
+ f"{key} must be an integer such that {lo} <= {key} <= {hi}"
+ )
+
def _set_pos_number(self, key: str, val: int, allow_inf: bool) -> None:
"""Set ``key`` to ``val`` if ``val`` is a positive integer."""
if isinstance(val, int) and val > -1:
@@ -541,6 +551,7 @@ class ManimConfig(MutableMapping):
"pixel_height",
"pixel_width",
"window_monitor",
+ "zero_pad",
]:
setattr(self, key, parser["CLI"].getint(key))
@@ -675,6 +686,7 @@ class ManimConfig(MutableMapping):
"fullscreen",
"use_projection_fill_shaders",
"use_projection_stroke_shaders",
+ "zero_pad",
]:
if hasattr(args, key):
attr = getattr(args, key)
@@ -1225,6 +1237,12 @@ class ManimConfig(MutableMapping):
doc="Use shaders for OpenGLVMobject stroke which are compatible with transformation matrices.",
)
+ zero_pad = property(
+ lambda self: self._d["zero_pad"],
+ lambda self, val: self._set_int_between("zero_pad", val, 0, 9),
+ doc="PNG zero padding. A number between 0 (no zero padding) and 9 (9 columns minimum).",
+ )
+
def get_dir(self, key: str, **kwargs: str) -> Path:
"""Resolve a config option that stores a directory.
diff --git a/manim/cli/render/output_options.py b/manim/cli/render/output_options.py
index a48aaed21..079594b7d 100644
--- a/manim/cli/render/output_options.py
+++ b/manim/cli/render/output_options.py
@@ -10,6 +10,13 @@ output_options = option_group(
default=None,
help="Specify the filename(s) of the rendered scene(s).",
),
+ option(
+ "-0",
+ "--zero_pad",
+ type=click.IntRange(0, 9),
+ default=None,
+ help="Zero padding for PNG file names.",
+ ),
option(
"--write_to_movie",
is_flag=True,
diff --git a/manim/scene/scene_file_writer.py b/manim/scene/scene_file_writer.py
index cae0acff4..81f566a26 100644
--- a/manim/scene/scene_file_writer.py
+++ b/manim/scene/scene_file_writer.py
@@ -290,9 +290,14 @@ class SceneFileWriter(object):
self.writing_process.stdin.write(frame.tobytes())
if is_png_format() and not config["dry_run"]:
target_dir, extension = os.path.splitext(self.image_file_path)
- Image.fromarray(frame).save(
- f"{target_dir}{self.frame_count}{extension}"
- )
+ if config["zero_pad"]:
+ Image.fromarray(frame).save(
+ f"{target_dir}{str(self.frame_count).zfill(config['zero_pad'])}{extension}"
+ )
+ else:
+ Image.fromarray(frame).save(
+ f"{target_dir}{self.frame_count}{extension}"
+ )
self.frame_count += 1
def save_final_image(self, image):
diff --git a/tests/test_scene_rendering/test_cli_flags.py b/tests/test_scene_rendering/test_cli_flags.py
index 5ef39d0ba..26d41a13f 100644
--- a/tests/test_scene_rendering/test_cli_flags.py
+++ b/tests/test_scene_rendering/test_cli_flags.py
@@ -361,7 +361,39 @@ def test_images_are_created_when_png_format_set(
out, err, exit_code = capture(command)
assert exit_code == 0, err
- expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png"
+ expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0000.png"
+ assert expected_png_path.exists(), "png file not found at " + str(expected_png_path)
+
+
+def test_images_are_zero_padded_when_zero_pad_set(
+ tmp_path, manim_cfg_file, simple_scenes_path
+):
+ """Test images are zero padded when --format png and --zero_pad n are set"""
+ scene_name = "SquareToCircle"
+ command = [
+ sys.executable,
+ "-m",
+ "manim",
+ "-ql",
+ "--media_dir",
+ str(tmp_path),
+ "--format",
+ "png",
+ "--zero_pad",
+ "3",
+ simple_scenes_path,
+ scene_name,
+ ]
+ out, err, exit_code = capture(command)
+ assert exit_code == 0, err
+
+ unexpected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle0.png"
+ assert not unexpected_png_path.exists(), "non zero padded png file found at " + str(
+ unexpected_png_path
+ )
+
+ expected_png_path = tmp_path / "images" / "simple_scenes" / "SquareToCircle000.png"
assert expected_png_path.exists(), "png file not found at " + str(expected_png_path)