opencv 读取视频, 从指定时间读取视频, 显示播放视频的进度
import cv2
from tqdm import tqdm
from termcolor import cprint
import time
cv2.namedWindow("image", cv2.WINDOW_NORMAL)
cv2.moveWindow("image", 0, 0)
cv2.resizeWindow("image", 960, 540)
def CV(path, start=0, end=None, wait=1):
"""
opencv读取视频
:param path: 视频路径
:param start: 视频开始时间
:param end: 视频结束时间
:param wait: 每帧等待时间
:return: None
"""
vc = cv2.VideoCapture(path)
opened = vc.isOpened()
if not opened:
cprint("视频打开错误", "red")
return
vc.set(cv2.CAP_PROP_FPS, 25)
vc.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
vc.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
fps = vc.get(cv2.CAP_PROP_FPS) ## 获取视频帧率
count = int(vc.get(cv2.CAP_PROP_FRAME_COUNT)) ## 获取视频总帧数
width = int(vc.get(cv2.CAP_PROP_FRAME_WIDTH)) ## 获取视频宽度
height = int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT)) ## 获取视频高度
print(f"视频宽度: {width}, 视频高度: {height}, 视频总帧数: {count}, 视频帧率: {fps}")
time.sleep(0.01)
if start:
start_frame = min(int(start * fps), count) # 开始帧
vc.set(cv2.CAP_PROP_POS_FRAMES, start_frame) ## 设置视频的开始帧位置
count -= start_frame
if end:
count -= count - min(int((end - start) * fps), count)
pbar = tqdm(total=count, desc="播放进度") ## 进度条
f_num = 0 ## 读取视频的帧数
while opened:
f_num += 1
opened, frame = vc.read()
if opened:
# frame = cv2.resize(frame, (0, 0), None, 0.5, 0.5)
cv2.imshow('image', frame)
pbar.update(1)
if cv2.waitKey(wait) == 27 or f_num == count:
break
else:
break
pbar.close()
vc.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
path = r"E:\lever\dataset\video\lever_06/front.mp4"
# path = r"rtsp://admin:[email protected]/h264/ch1/main/av_stream"
CV(path, 60, 80)