使用Moviepy实现缩放效果函数时遇维度广播错误求助
问题解决:Moviepy缩放效果函数出现形状不匹配错误
错误原因
错误提示operands could not be broadcast together with shapes (1280,720) (1280,720,3),核心问题是你手里的图片格式不统一:部分是单通道灰度图(数组形状为(1280,720)),另一部分是3通道RGB图(数组形状为(1280,720,3)),Moviepy处理时通道数不一致导致数组广播失败。
修复后的完整代码
import math from PIL import Image import numpy as np from moviepy.editor import VideoClip def zoom_in_effect(clip, zoom_ratio=0.025): def effect(get_frame, t): img_array = get_frame(t) # 把单通道灰度图转成3通道RGB格式,统一所有帧的通道数 if len(img_array.shape) == 2: img_array = np.stack([img_array]*3, axis=-1) img = Image.fromarray(img_array) base_size = img.size new_size = [ math.ceil(img.size[0] * (1 + (zoom_ratio * t))), math.ceil(img.size[1] * (1 + (zoom_ratio * t))) ] # 确保新尺寸为偶数 new_size[0] = new_size[0] + (new_size[0] % 2) new_size[1] = new_size[1] + (new_size[1] % 2) img = img.resize(new_size, Image.LANCZOS) x = math.ceil((new_size[0] - base_size[0]) / 2) y = math.ceil((new_size[1] - base_size[1]) / 2) img = img.crop([ x, y, new_size[0] - x, new_size[1] - y ]).resize(base_size, Image.LANCZOS) result = np.array(img) img.close() return result return clip.fl(effect)
关键修改说明
- 在将numpy数组转为PIL Image之前,增加了通道检查逻辑:如果数组是2维(单通道灰度图),就通过
np.stack复制三次通道,转换成3维RGB格式。 - 统一所有帧的通道数后,就不会再出现数组形状不匹配的广播错误。
内容的提问来源于stack exchange,提问作者fartoot
相关产品推荐
相关产品推荐

