python - 使用 cv2.videowrite() 创建的视频无法播放?
问题描述
import numpy
import cv2
import random
image=cv2.imread(r"C:\Users\Sriram\Desktop/img.png")
print(image.shape)
image=cv2.resize(image,(1080,600))
fourcc=cv2.VideoWriter_fourcc(*"MP4V")
def rand():
n=random.randrange(0,255,15)
x=random.randrange(0,255,15)
y=random.randrange(0,255,15)
return cv2.copyMakeBorder(image,40,40,40,40,cv2.BORDER_CONSTANT,None,(x,n,y))
#cv2.imwrite(r"C:\Users\Sriram\Desktop/new.jpg",image)
l=[rand() for i in range(30)]
print(l)
video=cv2.VideoWriter(r"C:\Users\Sriram\Desktop/video.mp4",fourcc,25,(1080,600))
for i in l:
video.write(i)
cv2.destroyAllWindows()
video.release()
这是我通过更改图像边框从图像创建视频的代码,它可以工作并输出视频文件。但是 当我尝试播放视频时,视频文件无法在我的电脑中打开,它是不正确的压缩代码fourcc,我尝试了不同fourcc“xvid”,“mpv4”,“mpjg”没有解决
解决方案
您的输出视频帧大小不正确。您的输入帧大小为 (1080,600)。我们在每边添加 40px 边框,所以最终的框架尺寸将是 (1080+40*2,600+40*2),即 (1160,680)
import numpy
import cv2
import random
image=cv2.imread(r"C:\Users\Sriram\Desktop/img.png")
print(image.shape)
image=cv2.resize(image,(1080,600))
fourcc=cv2.VideoWriter_fourcc(*"MP4V")
def rand():
n=random.randrange(0,255,15)
x=random.randrange(0,255,15)
y=random.randrange(0,255,15)
return cv2.copyMakeBorder(image,40,40,40,40,cv2.BORDER_CONSTANT,None,(x,n,y))
#cv2.imwrite(r"C:\Users\Sriram\Desktop/new.jpg",image)
l=[rand() for i in range(30)]
print(l)
video=cv2.VideoWriter(r"C:\Users\Sriram\Desktop/video.mp4",fourcc,25,(1160,680))
for i in l:
video.write(i)
cv2.destroyAllWindows()
video.release()
推荐阅读
- javascript - 使用 nodejs 和 puppeteer 从维基百科页面抓取影片
- github - GitHub 拉取请求未解决的评论
- java - Quarkus 和提供的依赖项 (sapjco3.jar)
- android - 为什么在我已经使用 !TextUtils.isEmpty() 时出现“NullPointerException”警告?
- c# - 当您可以在没有它的情况下进行 DI 设置时,IServiceCollection 的 Configure 方法的目的是什么?
- node.js - Ionic V1.4.3 需要哪个 node.js
- php - 为产品类别档案的顶级术语设置特定的列数
- c# - 如何分组列表
> 按类 ClassName 属性 - c++ - 使用大国的复杂性问题
- python - 文本输入时启用按钮