参考书目:《Python科学计算》,《OpenCV 3计算机视觉》
python3.6+open cv3
其他的库,截止到发博客位置,基本上都是最新的
根据《OpenCV 3计算机视觉》,参考《Python科学计算》改写
import cv2
#VideocCapture类用于从视频文件件或视频设备中读入图像
video = cv2.VideoCapture("C:\\Users\\Deskto\\Wildlife.wmv")
#根据名字即可看出用途
FPS = video.get(cv2.CAP_PROP_FPS)
print("fps:",FPS)
size = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)), int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print("width", size[0])
print("hight", size[1])
#视频总帧数
print("FRAMES", video.get(cv2.CAP_PROP_FRAME_COUNT))
#获取当前帧,此时为0
print("current FRAME", video.get(cv2.CAP_PROP_POS_FRAMES))
#读入一帧图像,它返回两个值,是否正确获得图像的布尔值和表示图像是数组
#正确读入一帧图像后,当前帧自动递增
res,frame0 = video.read()
if res == True:
cv2.imshow("demo1", frame0)
cv2.waitKey(0)
#此时当前帧为1
print("current FRAME", video.get(cv2.CAP_PROP_POS_FRAMES))
#可以通过set方法设置当前帧,从而直接读取视频中指定位置的图像
video.set(cv2.CAP_PROP_POS_FRAMES,300)
res,frame1 = video.read()
if res == True:
cv2.imshow("demo2", frame1)
cv2.waitKey(0)
#此时当前帧为301
print("current FRAME", video.get(cv2.CAP_PROP_POS_FRAMES))
#视频文件的写入
#参数分别为,要写入的视频文件名,视频编码器类型 'X','V','I','D'为MPEG4编码类型,FPS、size同上
#编码类型具体需要自行查看opencv的帮助文档
videoWriter = cv2.VideoWriter(
"C:\\Users\\xiaolong\\Desktop\\myvideo.avi",cv2.VideoWriter_fourcc('X','V','I','D'),FPS,size)
#将当前帧重新指定为0帧处
video.set(cv2.CAP_PROP_POS_FRAMES,0)
print("current FRAME", video.get(cv2.CAP_PROP_POS_FRAMES))
#循环按帧写入到新的视频文件中
res,frame1 = video.read()
while res:
videoWriter.write(frame1)
res,frame1 = video.read()
#释放文件
video.release()
上述结果如下:
fps: 29.97002997002997
width 1280
hight 720
FRAMES 902.0
current FRAME 0.0
current FRAME 1.0
current FRAME 301.0
current FRAME 0.0