上期我们主要是针对在视频中选择实时的fps,这期主要是讲讲用opencv显示进度条。这期也是在上期的基础上添加的代码
下面代码是上期代码中增加的效果
# coding=gbk
import time
import cv2
def nothing(emp):
pass
#设置窗口名称
cv2.namedWindow('frame')
cap = cv2.VideoCapture("D:\\jc\\Myself\\video\\Hacker_glasses_07_Videvo.mov") # 读取文件
start_time = time.time()
#用于记录帧数
counter = 0
# 获取视频宽度
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# 获取视频高度
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
#视频平均帧率
fps = cap.get(cv2.CAP_PROP_FPS)
# 获取视频帧数
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
loop_flag = 0
pos = 0
# 新建一个滑动条
cv2.createTrackbar('time', 'frame', 0, frames, nothing)
while (True):
if loop_flag == pos:
loop_flag = loop_flag + 1
cv2.setTrackbarPos('time', 'frame', loop_flag)
else:
pos = cv2.getTrackbarPos('time', 'frame')
loop_flag = pos
cap.set(cv2.CAP_PROP_POS_FRAMES, pos)
ret, frame = cap.read()
# 键盘输入空格暂停,输入q退出
key = cv2.waitKey(1) & 0xff
if key == ord(" "):
cv2.waitKey(0)
if key == ord("q"):
break
counter += 1 # 计算帧数
if (time.time() - start_time) != 0: # 实时显示帧数
cv2.putText(frame, "FPS {0}".format(float('%.1f' % (counter / (time.time() - start_time)))), (500, 50),
cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255),
3)
src = cv2.resize(frame, (frame_width // 2, frame_height // 2), interpolation=cv2.INTER_CUBIC) # 窗口大小
cv2.imshow('frame', src)
print("FPS: ", counter / (time.time() - start_time))
counter = 0
start_time = time.time()
time.sleep(1 / fps) # 按原帧率播放
cap.release()
cv2.destroyAllWindows()
下面代码是单独创建进度条的效果
import cv2
def nothing(emp):
pass
video = 'D:\\jc\\Myself\\video\\Hacker_glasses_07_Videvo.mov'
cv2.namedWindow('video')
cap = cv2.VideoCapture(video)
frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
loop_flag = 0
pos = 0
cv2.createTrackbar('time', 'video', 0, frames, nothing)
while 1:
if loop_flag == pos:
loop_flag = loop_flag + 1
cv2.setTrackbarPos('time', 'video', loop_flag)
else:
pos = cv2.getTrackbarPos('time', 'video')
loop_flag = pos
cap.set(cv2.CAP_PROP_POS_FRAMES, pos)
ret, img = cap.read()
cv2.imshow('video', img)
if cv2.waitKey(1) & loop_flag == frames:
break
cap.release()
cv2.destroyAllWindows()
在我们代码中需要注意,最开始创建窗口时的名称,以及创建滑动条的名称、展示出来的名称都要保持一致。