围绕图像的X轴旋转图像

2024-05-15 15:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要绕x轴(或y轴)旋转图像。我可以用avisynth轻松地创建这样的动画,但是现在我需要用Python的moviepy模块实现这种效果。我可以很容易地用下面的脚本旋转图像,但需要一些线索如何在二维或三维旋转它

enter image description here

from moviepy.editor import *

clip = ImageClip('my_image.jpg')
rotated_clip = (clip.add_mask()
                .fx(vfx.resize, width=300, height=300)
                .fx(vfx.rotate, lambda t: 90*t, expand=False)
                .set_duration(5))
final_clip = CompositeVideoClip([rotated_clip.set_pos("center")], size=(800,800), bg_color=3*[255])
final_clip.write_videofile("test.mp4", fps=25, codec="libx264")

下面是实际生成示例图像的avisynth脚本。请注意,它确实需要“QUAD”插件。在

^{pr2}$

Tags: 模块图像脚本clip动画finalfxset
1条回答
网友
1楼 · 发布于 2024-05-15 15:31:12

其中一种方法是使用Vapory,MoviePy作者的另一个库,它简化了通过Python对POV-Ray的操作。您可以在三维场景中创建一个矩形,并围绕任意轴旋转它,每隔一段时间将帧保存到MoviePy剪辑中。在

电影+蒸气代码

from moviepy.editor import concatenate, ImageClip, VideoClip
from vapory import *

img_path = './baseball.png'
img_clip = ImageClip(img_path)
W, H = img_clip.w, img_clip.h
AR = 1.0*W/H

# Set rotation rate by defining the period (in seconds) for 360 deg. revolution
t_rev = 2.0

t_half = t_rev/2.0  # The time required for a half revolution
t_still = 0.8 # How long (in seconds) to hold the half rotated image still


# Static POV-Ray objects
cam = Camera('location', [ 0,  0, -1],
             'look_at',  [ 0,  0,  0])
light = LightSource([0, 0, -1]) # Light at camera location
bg = Background('color', [0, 0, 0]) # Black background


def scene(t):
    """ Returns the scene at time 't' (in seconds) """
    s = Scene(camera = cam, objects = [light, bg])

    # Add POV-Ray box with image textured on it
    s = s.add_objects([
          Box([0, 0, 0],
              [W, H, 0],
              Texture(Pigment(ImageMap('"{}"'.format(img_path), 'once')),
                      Finish('ambient', 1.0)),
              'translate', [-0.5, -0.5, 0],
              'scale', [AR, 1, 0],
              'rotate', [0, (360/t_rev)*t, 0])]) # Can change axis of rotation here
    return s


def make_frame(t):
    return scene(t).render(width=W, height=H, antialiasing=0.1)


still_1 = VideoClip(make_frame).to_ImageClip(t=0).set_duration(t_still)
half_1  = VideoClip(make_frame).subclip(0, t_half)
still_2 = VideoClip(make_frame).to_ImageClip(t=t_half).set_duration(t_still)
half_2  = VideoClip(make_frame).subclip(t_half, t_rev)

final_clip = concatenate([still_1, half_1, still_2, half_2])
final_clip.write_gif("./baseball_rot.gif", fps=15)

输出GIF

enter image description here

其他想法:

您可能需要更改的主要内容是img_patht_rev(360度旋转的时间)、t_still和输出帧速率。在

我从您的示例图像中删除了一列像素,使其降到一个偶数宽度(150像素)。如果您只想制作gif,这并不重要,但是如果您想生成一个x264编码的MP4,那么您可能应该使用mod2维度。在

用射线跟踪器来解决这个问题似乎有些过分,但这是我提出的第一个有效的解决方案。我想将图像表示为3D场景中的2D矩形,在这里我可以简单地指定旋转角度,而3D库将处理其余部分。在

应该可以使用scikit图像的投影变换来解决这个问题,如this MoviePy example。请特别注意,trapzWarp函数位于代码列表的中间。在

相关问题 更多 >