我在一个python脚本中使用OpenCV将PIL格式的图像转换为MP4视频.
尽管我可以在创建视频后正常播放它们,但之后我无法将它们上传到Twitter或Instagram上.
如果在创建视频后,我使用外部视频转换器将创建的MP4视频转换为相同的MP4视频格式,它现在可以上传到Twitter和Instagram上.因此,这个问题一定与OpenCV的编码格式有关.
我试着使用不同的编解码器格式,而不是我在网上找到的与MP4视频兼容的任何四通道编码格式,但问题仍然存在.
我还可以try 在导出设置中更改哪些内容,以便能够直接上传使用OpenCV创建的视频?
以下是我使用的示例代码:
import cv2
import numpy as np
from PIL import Image as Img
#Create a list of PIL images:
PILimages = []
for i in range(20):
digit = str(i)
if i < 10:
digit = "0" + digit
image = Img.open("animationframes/frame " + digit + ".png")
PILimages.append(image)
#Convert the PIL image list to OpenCV format:
def PILimageGroupToOpenCV(imageGroup):
openCVimages = []
for image in imageGroup:
opencvImage_ = np.asarray(image)
opencvImage_ = cv2.cvtColor(opencvImage_, cv2.COLOR_RGB2BGR)
openCVimages.append(opencvImage_)
return openCVimages
#Save the frames as an MP4 video using openCV:
def SavePILimagesToMp4(images,PathAndName,FPS):
#Convert the PIL images to numpy and then to OpenCV:
openCVimages = PILimageGroupToOpenCV(images)
#Create the new video:
height,width, layers = openCVimages[0].shape
size = (width,height)
video = cv2.VideoWriter(PathAndName, cv2.VideoWriter_fourcc(*'mp4v'), FPS, size)
#Add the images as frames into the video:
for i in range(len(openCVimages)):
video.write(openCVimages[i])
video.release()
#Save the pil images:
SavePILimagesToMp4(PILimages,"out.MP4",25)