获取视频帧数和总帧数代码
import cv2
videoPath=input("请输入视屏文件的绝对路径:")
# 将视频文件路径转化为标准的路径
videoPath=videoPath.replace("\\","/").replace('"','').replace("'","").strip()
# 视屏获取
videoCapture=cv2.VideoCapture(videoPath)
# 帧率(frames per second)
fps = videoCapture.get(cv2.CAP_PROP_FPS)
# 总帧数(frames)
frames = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
print("帧数:"+str(fps))
print("总帧数:"+str(frames))
print("视屏总时长:"+"{0:.2f}".format(frames/fps)+"秒")
其他
在三维重构或其他项目中,往往需要获取每一张图片的时间戳,这时可以使用如下代码:
import time
print("{:.6f}".format(time.time()))
1
2
demo:
04-应用
import os
import cv2
import time
videoPath=input("请输入视屏文件的绝对路径:")
# 将视频文件路径转化为标准的路径
videoPath=videoPath.replace("\\","/").replace('"','').replace("'","")
# 视屏获取
videoCapture=cv2.VideoCapture(videoPath)
# 帧率(frames per second)
fps = videoCapture.get(cv2.CAP_PROP_FPS)
# 总帧数(frames)
frames = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)
#图片存储地址:
pathSave="./data/rgb/"
if(os.path.exists(pathSave)!=True):
os.makedirs(pathSave)
#间隔多少帧取一张图片
skipNum=2 #注:间隔2帧取一个图;
count=0
f=open("./data/"+"rgb.txt","w",encoding="utf-8")
f.write("# timestamp filename\n")
while (True):
ret,frame=videoCapture.read()
if(ret):
if(count%(skipNum+1)==0):
imgName="{:.6f}".format(time.time()+1.0*skipNum/fps-0.001*skipNum)
imgPath=" rgb/"+imgName+ '.png'
cv2.imwrite(pathSave + imgName + '.png', frame)
f.write(imgName+imgPath+"\n")
count+=1
# cv2.waitKey(int(1.0*skipNum/fps*1000))
cv2.waitKey(1)
# time.sleep()
else:
print("视屏处理完毕!")
break
videoCapture.release()
f.close()