python - 无法在 OpenCV Python 中读取 MP4 和 avi 文件
问题描述
我只想使用 OpenCV 读取和显示 MP4 视频,为此我编写了以下基本代码:
import cv2
input_video_path = './Input Video/Input_video1.mp4'
cap = cv2.VideoCapture(input_video_path)
while(cap.isOpened()):
ret, frame = cap.read()
print(frame, ret)
cv2.imshow("frame", frame)
cap.release()
cv2.destroyAllWindows()
当我运行它时,它读取第一几帧,然后所有其他帧是None
:
[[[ 7 14 27]
[ 7 14 27]
[ 7 14 27]
...
...
[ 60 57 64]
[ 70 62 64]
[ 72 64 66]]] True
None False
Traceback (most recent call last):
File "D:/Project/ML IP and Coding/Cynapto_Task/exploring_face_detection_methods.py", line 10, in <module>
cv2.imshow("frame", frame)
cv2.error: OpenCV(3.4.2) C:\Miniconda3\conda-bld\opencv-suite_1534379934306\work\modules\highgui\src\window.cpp:356: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
我还打印了ret
确认相同行为的变量。我尝试了 2-3 个不同的视频,甚至使用.avi
格式,但得到了相同的结果。
我在网上搜索了解决方案,但只能找到有关编解码器和在我的虚拟环境中安装编解码器的信息。我对视频文件格式和编解码器知之甚少。
有人可以帮我弄这个吗?
我在用:
Python 3.7,操作系统:Windows,环境:conda,OpenCV v4.5.0
解决方案
如果您收到ret
,False
则意味着视频到达结束帧。如果视频未完成但您收到False
了,则它可能已损坏。
试试这个代码:
import cv2
input_video_path = './Input Video/Input_video1.mp4'
cap = cv2.VideoCapture(input_video_path)
while(cap.isOpened()):
ret, frame = cap.read()
print(frame, ret)
if ret:
cv2.imshow("frame", frame)
cv2.waitKey(1)
else:
break
cap.release()
cv2.destroyAllWindows()
推荐阅读
- google-sheets - 如何计算 Google 表格中特定单元格中的字数?
- angular - Angular 新手,无法从组件外部访问变量
- php - 将php、mysql和VB.net打包在一起
- python - python中的直方图函数
- angular - 我没有在 mergeMap 中使用 httpClient.get Observable 获取任何数据
- r - 合并两个具有非唯一标识符的数据帧
- ruby-on-rails - 充当可标记的对象 - 枚举方法在标记表中不起作用
- python - 在什么情况下 Tkinter 的 grid() 不能与 pack() 混合使用?
- c - 为什么当我使用 64 位局部变量时堆栈指针不减少?
- sql-server - 删除重复的行并使用重复的行 id 更新行