Skip to content

Video editing with Python

Add 'center', 'translate' and 'bg_color' arguments to 'rotate' FX (#1474)

Álvaro Mondéjar143618cf5f77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8d9d963..bb35abaa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Support for retrieve clip frames number using `clip.n_frames` [\#1471](https://github.com/Zulko/moviepy/pull/1471)
- `video.io.ffmpeg_reader.ffmpeg_parse_infos` returns data from all streams by FFmpeg inputs in attribute `inputs` [\#1466](https://github.com/Zulko/moviepy/pull/1466)
- `video.io.ffmpeg_reader.ffmpeg_parse_infos` returns metadata of the container in attribute `metadata` [\#1466](https://github.com/Zulko/moviepy/pull/1466)
+- `center`, `translate` and `bg_color` arguments to `video.fx.rotate` [\#1474](https://github.com/Zulko/moviepy/pull/1474)
### Changed <!-- for changes in existing functionality -->
- Lots of method and parameter names have been changed. This will be explained better in the documentation soon. See https://github.com/Zulko/moviepy/pull/1170 for more information. [\#1170](https://github.com/Zulko/moviepy/pull/1170)
diff --git a/moviepy/video/fx/rotate.py b/moviepy/video/fx/rotate.py
index 7288a78e..3aa08d12 100644
--- a/moviepy/video/fx/rotate.py
+++ b/moviepy/video/fx/rotate.py
@@ -1,93 +1,152 @@
+import warnings
+
import numpy as np
try:
- from PIL import Image
+ import PIL
- PIL_FOUND = True
+ PIL_rotate_kwargs_supported = {
+ # [moviepy rotate argument name,
+ # PIL.rotate argument supported,
+ # minimum PIL version required]
+ "fillcolor": ["bg_color", False, (5, 2, 0)],
+ "center": ["center", False, (4, 0, 0)],
+ "translate": ["translate", False, (4, 0, 0)],
+ }
- def pil_rotater(pic, angle, resample, expand):
- # Ensures that pic is of the correct type
- return np.array(
- Image.fromarray(np.array(pic).astype(np.uint8)).rotate(
- angle, expand=expand, resample=resample
- )
- )
+ if hasattr(PIL, "__version__"):
+ # check support for PIL.rotate arguments
+ PIL__version_info__ = tuple(int(n) for n in PIL.__version__ if n.isdigit())
+ for PIL_rotate_kw_name, support_data in PIL_rotate_kwargs_supported.items():
+ if PIL__version_info__ >= support_data[2]:
+ PIL_rotate_kwargs_supported[PIL_rotate_kw_name][1] = True
-except ImportError:
- PIL_FOUND = False
+ Image = PIL.Image
-
-def rotate(clip, angle, unit="deg", resample="bicubic", expand=True):
+except ImportError:
+ Image = None
+
+
+def rotate(
+ clip,
+ angle,
+ unit="deg",
+ resample="bicubic",
+ expand=True,
+ center=None,
+ translate=None,
+ bg_color=None,
+):
"""
Rotates the specified clip by ``angle`` degrees (or radians) anticlockwise
- If the angle is not a multiple of 90 (degrees), the package ``pillow`` must
- be installed, and there will be black borders. You can make them
- transparent with
+ If the angle is not a multiple of 90 (degrees) or ``center``, ``translate``,
+ and ``bg_color`` are not ``None``, the package ``pillow`` must be installed,
+ and there will be black borders. You can make them transparent with:
>>> new_clip = clip.add_mask().rotate(72)
Parameters
===========
- clip
- A video clip
+ clip : VideoClip
+ A video clip.
+
+ angle : float
+ Either a value or a function angle(t) representing the angle of rotation.
+
+ unit : str, optional
+ Unit of parameter `angle` (either "deg" for degrees or "rad" for radians).
- angle
- Either a value or a function angle(t) representing the angle of rotation
+ resample : str, optional
+ An optional resampling filter. One of "nearest", "bilinear", or "bicubic".
- unit
- Unit of parameter `angle` (either `deg` for degrees or `rad` for radians).
- Default: `deg`
+ expand : bool, optional
+ If true, expands the output image to make it large enough to hold the
+ entire rotated image. If false or omitted, make the output image the same
+ size as the input image.
- resample
- One of "nearest", "bilinear", or "bicubic".
+ translate : tuple, optional
+ An optional post-rotate translation (a 2-tuple).
- expand
- Only applIf False, the clip will maintain the same True, the clip will be
- resized so that the whole
+ center : tuple, optional
+ Optional center of rotation (a 2-tuple). Origin is the upper left corner.
+
+ bg_color : tuple, optional
+ An optional color for area outside the rotated image. Only has effect if
+ ``expand`` is true.
"""
- if PIL_FOUND:
- resample = {
- "bilinear": Image.BILINEAR,
- "nearest": Image.NEAREST,
- "bicubic": Image.BICUBIC,
- }[resample]
+ if Image:
+ try:
+ resample = {
+ "bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "bicubic": Image.BICUBIC,
+ }[resample]
+ except KeyError:
+ raise ValueError(
+ "'resample' argument must be either 'bilinear', 'nearest' or 'bicubic'"
+ )
if hasattr(angle, "__call__"):
- # angle is a function
get_angle = angle
else:
- # angle is a constant so convert to a constant function
- def get_angle(t):
- return angle
+ get_angle = lambda t: angle
def filter(get_frame, t):
-
angle = get_angle(t)
im = get_frame(t)
if unit == "rad":
angle = 360.0 * angle / (2 * np.pi)
- transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]
-
angle %= 360
- if (angle == 0) and expand:
- return im
- if (angle == 90) and expand:
- return np.transpose(im, axes=transpose)[::-1]
- elif (angle == 270) and expand:
- return np.transpose(im, axes=transpose)[:, ::-1]
- elif (angle == 180) and expand:
- return im[::-1, ::-1]
- elif not PIL_FOUND:
+ if not center and not translate and not bg_color:
+ if (angle == 0) and expand:
+ return im
+ if (angle == 90) and expand:
+ transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]
+ return np.transpose(im, axes=transpose)[::-1]
+ elif (angle == 270) and expand:
+ transpose = [1, 0] if len(im.shape) == 2 else [1, 0, 2]
+ return np.transpose(im, axes=transpose)[:, ::-1]
+ elif (angle == 180) and expand:
+ return im[::-1, ::-1]
+
+ if not Image:
raise ValueError(
'Without "Pillow" installed, only angles that are a multiple of 90'
+ " without centering, translation and background color transformations"
' are supported, please install "Pillow" with `pip install pillow`'
)
- else:
- return pil_rotater(im, angle, resample=resample, expand=expand)
+
+ # build PIL.rotate kwargs
+ kwargs, _locals = ({}, locals())
+ for PIL_rotate_kw_name, (
+ kw_name,
+ supported,
+ min_version,
+ ) in PIL_rotate_kwargs_supported.items():
+ # get the value passed to rotate FX from `locals()` dictionary
+ kw_value = _locals[kw_name]
+
+ if supported: # if argument supported by PIL version
+ kwargs[PIL_rotate_kw_name] = kw_value
+ else:
+ if kw_value is not None: # if not default value
+ warnings.warn(
+ f"rotate '{kw_name}' argument not supported by your"
+ " Pillow version and is being ignored. Minimum Pillow version"
+ f" required: v{'.'.join(str(n) for n in min_version)}",
+ UserWarning,
+ )
+
+ # call PIL.rotate
+ return np.array(
+ Image.fromarray(np.array(im).astype(np.uint8)).rotate(
+ angle, expand=expand, resample=resample, **kwargs
+ )
+ )
return clip.transform(filter, apply_to=["mask"])