用OpenCV打开视频

0 投票
1 回答
1575 浏览
提问于 2025-04-18 16:34

我正在尝试按照这里的教程在OpenCV中打开一个视频文件,链接是OpenCV Python教程

但是,当我运行这段代码时,什么也没有发生。我的代码如下:

import numpy as np
import cv2

cap = cv2.VideoCapture('768x576.avi')   

while(cap.isOpened()):
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

我在系统上安装了ffmpeg,并且它在我的系统路径中。此外,我的机器上也安装了gstreamer。这个文件可以在Windows媒体播放器中打开,也可以在ffmpeg中处理,还可以在VLC中打开。

我对此感到很困惑,因为这应该是一个简单明了的教程。


编辑1:我安装了很多不同的编解码器,包括K-Lite Codec Pack和XVid。如果我用ffmpeg -i打开这个文件,得到的结果是:

C:\sandbox>ffmpeg -i 768x576.avi
ffmpeg version N-64539-gc8b2cf4 Copyright (c) 2000-2014 the FFmpeg developers
  built on Jul  8 2014 22:10:23 with gcc 4.8.3 (GCC)
  configuration: --enable-gpl --enable-version3 --disable-w32threads --enable-av
isynth --enable-bzlib --enable-fontconfig --enable-frei0r --enable-gnutls --enab
le-iconv --enable-libass --enable-libbluray --enable-libcaca --enable-libfreetyp
e --enable-libgme --enable-libgsm --enable-libilbc --enable-libmodplug --enable-
libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libope
njpeg --enable-libopus --enable-librtmp --enable-libschroedinger --enable-libsox
r --enable-libspeex --enable-libtheora --enable-libtwolame --enable-libvidstab -
-enable-libvo-aacenc --enable-libvo-amrwbenc --enable-libvorbis --enable-libvpx
--enable-libwavpack --enable-libwebp --enable-libx264 --enable-libx265 --enable-
libxavs --enable-libxvid --enable-decklink --enable-zlib
  libavutil      52. 91.100 / 52. 91.100
  libavcodec     55. 68.102 / 55. 68.102
  libavformat    55. 45.100 / 55. 45.100
  libavdevice    55. 13.102 / 55. 13.102
  libavfilter     4. 10.100 /  4. 10.100
  libswscale      2.  6.100 /  2.  6.100
  libswresample   0. 19.100 /  0. 19.100
  libpostproc    52.  3.100 / 52.  3.100
Input #0, avi, from '768x576.avi':
  Metadata:
    encoder         : MEncoder 2:1.0~rc2-0ubuntu19
  Duration: 00:01:19.50, start: 0.000000, bitrate: 818 kb/s
    Stream #0:0: Video: msmpeg4v3 (div3 / 0x33766964), yuv420p, 768x576, 816 kb/
s, 10 fps, 10 tbr, 10 tbn, 10 tbc
At least one output file must be specified

编辑2:当我尝试逐行执行时,发生了以下情况:

C:\sandbox>python
Python 2.7.7 |Anaconda 2.0.1 (64-bit)| (default, Jun 11 2014, 10:40:02) [MSC v.1
500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>>
>>> import numpy as np
>>> import cv2
>>> print cv2.__version__
2.4.9
>>>
>>> cap = cv2.VideoCapture('768x576.avi')
>>> print cap
<VideoCapture 0000000002DC3810>
>>> print cap.get(5)
0.0
>>>

编辑3:虽然答案不是100%的解决方案,但评论中提到的一些内容让我找到了这个链接OpenCV VideoCapture在Python中无法读取视频,但在VS11中可以,通过这个我找到了我的问题所在。

1 个回答

1

如果你在使用Windows系统,并且你确定自己成功打开了这个文件,那么很可能你需要安装一个解码器包

撰写回答