本文最后更新于:2024年1月14日 晚上

视频由图像连续切换构成,本文记录python提取视频中图像的方法。

核心方法

  • 使用opencv 库 中的VideoCapture 方法:
1
2
3
4
import cv2
cap = cv2.VideoCapture(url)
cap.set(1, 1) # 取它的第一帧
rval, frame = cap.read() # rval 为是否成功的标记(True为正常), frame 为截取的图像

工具代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-

import cv2
from PIL import Image
from io import BytesIO
import random
import time
import functools
import matplotlib.pyplot as plt


def tryTime(maxTry, timeout=random.random()):
"""
重试
:param maxTry:重试次数
:param timeout:睡眠时间
:return:
"""
def wrap1(func):
#functools.wraps 可以将原函数对象的指定属性复制给包装函数对象,
@functools.wraps(func)
def __decorator(*args,**kwargs):
tryTime = 0
while tryTime < maxTry:
try:
return func(*args,**kwargs)
except Exception:
pass
# print("TryTime_except==%s"%traceback.format_exc())
# logDebug("tryTime","TryTime_except==%s"%traceback.format_exc())
tryTime += 1
time.sleep(timeout)
return __decorator
return wrap1

@tryTime(2)
def get_video_cover(url):
cap = cv2.VideoCapture(url)
rate = cap.get(5)
frame_number = cap.get(7) # 视频文件的帧数
if rate==0:
duration=0
else:
duration = int(frame_number / rate) # 单位秒
cap.set(1, 1) # 取它的第一帧
rval, frame = cap.read() # 如果rval为False表示这个视频有问题,为True则正常

data = cv2.imencode(".jpg", frame)[1].tobytes() # 将图片转为jpg格式的二进制流
cap.release()
height = frame.shape[0] # 高度
width = frame.shape[1] # 宽度
return rval, frame, duration, width, height


def get_image_size(data):
im = Image.open(BytesIO(data))
return im.size


if __name__ == '__main__':

url = r'https://uipv4.zywvvd.com:33030/HexoFiles/win11-mt/20210909140933.mp4'
rval, frame, duration, width, height = get_video_cover(url)
print(rval)
plt.imshow(frame)
plt.show()

pass

  • 代码可以直接运行,运行结果:

参考资料



文章链接:
https://www.zywvvd.com/notes/coding/python/python-extract-img-from-video/python-extract-img-from-video/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Python 从视频中提取图像
https://www.zywvvd.com/notes/coding/python/python-extract-img-from-video/python-extract-img-from-video/
作者
Yiwei Zhang
发布于
2021年9月15日
许可协议