opencv + python打开usb相机,录制视频并保存及读取视频

1.录制视频并保存


import datetime   #显示时间所需模块
import cv2
 
#创建VideoWriter为写多媒体文件
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
vw = cv2.VideoWriter(".\\out1.mp4",fourcc,25,(640,480))
 
#创建窗口
cv2.namedWindow('video',cv2.WINDOW_NORMAL)
cv2.resizeWindow('video',640,480)  #设置窗口大小
 
#获取视频设备
cap = cv2.VideoCapture(0)
#cap = cv2.VideoCapture("文件地址")   从文件获取视频
flag = 0 
while cap.isOpened():    #判断摄像头是否已打开,若打开返回值则为True
    #从摄像头读视频帧
    ret,frame = cap.read()
    if ret ==True : #判断是否读取到数据
        #将视频帧在窗口中显示
        #函数执行开始时间

        timer = cv2.getTickCount()
    
        #计算fps
    
        fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
    
        #显示提示信息(图像,文字内容,坐标,字体,大小,颜色,字体厚度) #cv2.LINE_AA为抗锯齿,看起来会平滑一些   
        cv2.putText(frame, "FPS : " + str(int(fps)), (100, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.85, (150, 170, 50), 2, cv2.LINE_AA)
    
        #显示时间    
        datet = str(datetime.datetime.now())[0:19]    
        cv2.putText(frame, "Time:" + datet, (100, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.85,(0, 255, 255), 2, cv2.LINE_AA)
        if flag ==0:   
            cv2.putText(frame, "image collecting~" , (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.85,(0, 255,  ), 2, cv2.LINE_AA)
        cv2.imshow('video',frame)
        cv2.resizeWindow('video',640,480)  #重新设置窗口大小
        #写数据到多媒体文件
        key = cv2.waitKey(1)
        # print('flag ==')
        # print(flag)
        if flag ==1:
            # print('开始保存图像')
            cv2.putText(frame, "image saving~" , (100, 80), cv2.FONT_HERSHEY_SIMPLEX, 0.85,(0, 255, 0), 2, cv2.LINE_AA)
            cv2.imshow('video',frame)
            cv2.resizeWindow('video',640,480)  #重新设置窗口大小                      
            cv2.waitKey(1 )
            vw.write(frame) 
        if key == 32:#按空格键开始保存图像
            vw.write(frame)
            flag = 1      
        # key = cv2.waitKey(1000)
        elif (key &0xFF == ord('s')): #按s键停止保存图像
            flag =0
            print('停止保存图像')
        elif(key & 0xFF == ord('q')):#按q键退出
            print('结束采集图像')
            break
    else:
        break
#释放资源
cap.release() #释放VideoCapture
vw.release() #释放VideoWrite
cv2.destroyAllWindows()  #释放窗口资源

2.读取保存的视频

# -*- coding: utf-8 -*-
from openni import openni2
import numpy as np
import cv2


cv2.namedWindow('video',cv2.WINDOW_NORMAL)
video = cv2.VideoCapture('.\\out1.mp4')
while video.isOpened():
    open,frame = video.read()
    # print(open)
    if open:
        # gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)
        # cv2.imshow('video',gray)
        # key =cv2.waitKey(10)
        # if key ==27:
        cv2.imshow('video',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
video.release() #释放VideoCapture

cv2.destroyAllWindows()  #释放窗口资源

录制效果如下:
opencv + python打开usb相机,录制视频并保存及读取视频_第1张图片

你可能感兴趣的:(opencv,python,计算机视觉)