Python OpenCV视频格式浏览器播放

Python OpenCV video format play in browser

我正在尝试从一系列图像创建视频并在浏览器中显示它,但出于某种奇怪的原因,无论我使用哪种编解码器或文件格式,我都会收到以下错误:

No video with supported format and mime type found

这是我的代码:

ready_images = []
import cv2

for img in videos['Images']:
    image = cv2.imread(img.fileName)
    ready_images.append(image)

fourcc = cv2.VideoWriter_fourcc(*'MP4V')

video_name = videos['Images'][0].gifLocationPath + "//" + videos['Name']
frame = cv2.imread(videos['Images'][0].fileName)
height, width, layers = frame.shape

video_name = video_name[:-4]+".mp4"
video = cv2.VideoWriter(video_name, fourcc, 20.0, (width, height))

for image in ready_images:
    video.write(image)

cv2.destroyAllWindows()
video.release()

有趣的是,在 Firefox 或 Chrome 中,视频不起作用,但在 Edge 中......它们确实有效。

我不想使用 FFMPEG,更愿意让它与 OpenCV 一起使用。

如果你们中有人知道我应该使用什么格式的视频(我知道网络格式是 webm、ogg、mp4)或编解码器,请告诉我。

谢谢。

大多数浏览器不支持 MP4V 或 MPEG-4 第 2 部分,您可能想试试 H.264(MPEG-4 第 10 部分)。

为此,更改:

fourcc = cv2.VideoWriter_fourcc(*'MP4V')

fourcc = cv2.VideoWriter_fourcc(*'H264')

如果您使用的是Python3,请改用以下十六进制代码(使用四字节表示法时似乎有错误):

fourcc = 0x00000021

运行 脚本,您可能会收到以下错误消息:

Failed to load OpenH264 library: openh264-1.6.0-win32msvc.dll Please check environment and/or download library: https://github.com/cisco/openh264/releases

您需要按照消息中的说明进行操作,从 github 下载所需的库并将其放置在您的 PATH 可访问的位置。

使用 H.264 压缩,您还将获得更小的文件,这更适合 Web。

我知道这个问题很老了,但对于正在为 Web 浏览器寻找兼容的编解码器 + 容器的每个人来说: VP8 或 VP80 是兼容的编码器

cv2.VideoWriter_fourcc('V','P','8','0')

我将它与 .webM 作为容器一起使用。

Native WebM support by Mozilla Firefox,[7][8] Opera,[9][10] and Google Chrome[11] was announced at the 2010 Google I/O conference

https://en.wikipedia.org/wiki/WebM

它就像一个魅力,并且性能非常好,尽管 出于某种原因,我在创建 videoWriter 对象时遇到了这个错误:

OpenCV: FFMPEG: tag 0x30385056/'VP80' is not supported with codec id 139 and format 'webm / WebM'

获取.webm后缀的音频文件。

fourcc = cv2.VideoWriter_fourcc(*'vp80')
video_writer = cv2.VideoWriter('file.webm', fourcc, 20, (640, 480))

在html中:

<body>
<video width="320" height="240" controls>
    <source src="file.webm" type="video/webm">
</video>
</body>

它适用于 centos7 和 Windows10。

我按 fourcc=-1 打印所有可用的 mp4 编解码器。

之后我检查对我有用的编解码器。我看到那里 avc1。 所以我写了这样的代码:

fourcc = cv2.VideoWriter_fourcc(*'avc1')

打印代码时,您还会看到它们是小写的。