zoukankan      html  css  js  c++  java
  • 『OpenCV3』处理视频&摄像头

    在opencv中,摄像头和视频文件并没有很大不同,都是一个可以read的数据源,使用cv2.VideoCapture(path).read()可以获取(flag,当前帧),对于每一帧,使用图片处理函数即可。

    调用摄像头并记录为文件:

    # 摄像头读取并写入文件
    cameraCapture = cv2.VideoCapture(0)           # 获取摄像头对象
    fps = 30
    size = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), 
            int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    print(size)
    videoWriter = cv2.VideoWriter('OutputVid.flv', cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), fps, size)  # 生成书写器对象
    # 成功与否flag, 下一帧图像
    success, frame = cameraCapture.read()         # 摄像头对象读取数据
    # 10s * 30fps
    numFrameRamaining = 10 * fps - 1
    print(success)
    while success and numFrameRamaining > 0:
        videoWriter.write(frame)                  # 书写器对象记录帧
        success, frame = cameraCapture.read()     # 摄像头对象
        numFrameRamaining -= 1                    # 利用帧数计时:10s * 30fps
    cameraCapture.release()
    

     读取本地视频文件并另存为:

    和上面的流程几乎完全一样,只是对象由摄像头设备代号0改为视频文件路径

    import cv2
    # 读取本地视频并另存为
    videoCapture = cv2.VideoCapture('OutputVid.flv')
    fps = videoCapture.get(cv2.CAP_PROP_FPS)
    size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)), 
            int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
    videoWriter = cv2.VideoWriter('OutputVid2.flv', cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), fps, size)
    success, frame = videoCapture.read()
    while success:
        videoWriter.write(frame)
        success, frame = videoCapture.read()
    videoCapture.release()
    print('finalish')
    

     显示图片:

    import cv2
    
    img = cv2.imread('img2.jpg')
    cv2.namedWindow("Image")    # 可加可不加,加上的话一般和imshow之间会定义一些窗口事件处理用函数
    cv2.imshow('Image', img)    # 显示图片
    cv2.waitKey()
    cv2.destroyAllWindows()     # 释放所有窗口
    

     

    窗口事件相应函数&视频播放:

    0表示主摄像头,1表示前置摄像头。

    本程序调用摄像头,并实时输出,键盘输入ESC或点击窗口时会退出窗口。

    import cv2  
    
    clicked = False
    def onMouse(event, x, y, flags, param):
        global clicked
        if event == cv2.EVENT_LBUTTONUP:                      # 更多鼠标事件详见书26页
            clicked = True
    cv2.namedWindow('video')
    cv2.setMouseCallback('video', onMouse)                    # 设置鼠标事件,对应窗口检测到的数据会传入接收函数中
    
    print('摄像头已启动,键盘输入ESC或者鼠标左击窗口关闭摄像头')
    cameraCapture = cv2.VideoCapture(0)  
    if cameraCapture.isOpened():
        while True:
            success, frame = cameraCapture.read()
            if success:
                cv2.imshow('video', frame)  
            else:
                break
            if cv2.waitKey(20) == 27 or clicked:              # cv2.waitKey()中20表示每次等待20毫秒,默认返回-1,接收ESC时返回27(就是返回ASCII实际)
                break  
    cv2.destroyAllWindows()
    

     。

  • 相关阅读:
    栈的实现方式
    复合和继承
    循环链表和双向链表
    抽象类和接口
    private构造器和单例模式
    内部类
    关于初始化和清理
    多态的理解
    幾個小知識
    Youth
  • 原文地址:https://www.cnblogs.com/hellcat/p/7054511.html
Copyright © 2011-2022 走看看