Skip to content

图像 视频的加载与展示

创建窗口、加载图片、保存图片

  • namedWindow():创建一个窗口,并且给窗口起一个名字,在显示窗口的时候就可以指定显示哪一个窗口。
  • imshow():显示窗口。
  • destroyAllWindows():释放窗口。
  • resizeWindow:重置窗口尺寸
  • imread():读取图片资源
  • imwrite():写入图片

    import cv2
    
    cv2.namedWindow('img', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('img', 320, 240)
    
    img = cv2.imread("/Users/elasticnotes/Desktop/opencv/video/face.jpg")
    
    # 防止键盘事件导致中断
    while True:
    
        cv2.imshow('img', img)
    
        key = cv2.waitKey(0)
    
        if(key & 0xFF == ord('q')):
            break
        elif(key & 0xFF == ord('s')):
            cv2.imwrite("/Users/elasticnotes/Desktop/opencv/video/save.jpg", img)
        else:
            print(key)
    
    cv2.destroyAllWindows()
    

视频采集(从摄像头中读取视频)

  • VideoCaptrue(设备id, 支持的API1):虚拟采集器,调用时填写一个设备号,默认第一个摄像头为0
  • cap.read():一帧一帧将采集到的视频读取出来,返回两个值,第一个为状态值 读到帧为true,第二个为具体的视频帧
  • cap.release():将capture资源释放

    from ast import If
    import cv2
    
    cv2.namedWindow('video', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('video', 640, 480)
    
    # 获取视频设备
    cap = cv2.VideoCapture(0)
    
    while True:
        # 从摄像头读取视频帧
        ret, frame = cap.read()
    
        # 将视频帧在窗口中显示
        cv2.imshow('video', frame)
    
        # 等待键盘事件,如果为q,退出
        key = cv2.waitKey(1) # 此处不能一直等待 0为一直等待
        if (key & 0xFF == ord('q')):
            break;
    
    # 释放VideoCapture
    cap.release()
    
    # 销毁窗口
    cv2.destroyAllWindows();
    

    Image title
    执行结果

从多媒体中读取视频帧

# 读取视频文件,直接写入资源地址即可
cap = cv2.VideoCapture("/Users/elasticnotes/Desktop/opencv/video/video.mp4")
key = cv2.waitKey(40) # 根据视频原始帧率FPS,计算每帧正确的毫秒数。

视频录制

  • VideoWrite:视频写入
    1. 参数一为输出文件
    2. 参数二为多媒体文件格式(VideoWrite_fourcc)
    3. 参数三为帧率
    4. 参数四为分辨率大小
  • write:写入
  • release:关闭,释放资源,将缓冲区的内容写入到磁盘。
    import cv2
    
    #创建VideoWriter为写多媒体文件
    fourcc = cv2.VideoWriter_fourcc(*'MJPG')
    vw = cv2.VideoWriter('./out.mp4', fourcc, 25, (1280, 720))
    
    #创建窗口
    cv2.namedWindow('video', cv2.WINDOW_NORMAL)
    cv2.resizeWindow('video', 1280, 720)
    
    #获取视频设备/从视频文件中读取视频帧
    cap = cv2.VideoCapture(0)
    
    #判断摄像头是否为打开关态
    while cap.isOpened():
        #从摄像头读视频帧
        ret, frame = cap.read()
    
        if ret == True:
            #将视频帧在窗口中显示
            cv2.imshow('video', frame)
            #重新将窗口设备为指定大小
            cv2.resizeWindow('video', 1280, 720)
    
            #写数据到多媒体文件
            vw.write(frame)
    
            #等待键盘事件,如果为q,退出
            key = cv2.waitKey(1)
            if(key & 0xFF == ord('q')):
                break
        else:
            break
    
    #释放VideoCapture
    cap.release()
    
    #释放VideoWriter
    vw.release()
    
    #vw.release()
    cv2.destroyAllWindows()
    

控制鼠标

  • setMouseCallback(winname 窗口名称, callback 回调方法, userdata 传递数据 会从回调方法中传入)
  • callback(event, x, y, flags, userdata)
    • event2: 鼠标移动、按下左键...
    • x, y: 鼠标坐标
    • flags3: 鼠标键及组合键
      import cv2
      import numpy as np
      
      # 鼠标回调函数
      def mouse_callback(event, x, y, flags, userdata):
          print(event, x, y, flags, userdata)
      
      # 创建窗口
      cv2.namedWindow('mouse', cv2.WINDOW_NORMAL)
      cv2.resizeWindow('mouse', 640, 360)
      
      # 设置鼠标回调
      cv2.setMouseCallback('mouse', mouse_callback, "123")
      
      # 显示窗口和背景 zeros可以生成一个指定宽高的图像,图像内容全是0,zeros(高, 宽, 由于是bgr 所以是3个)
      img = np.zeros((360, 640, 3), np.uint8)
      while True:
          cv2.imshow('mouse', img)
          key = cv2.waitKey(1)
          if key & 0xFF == ord('q'):
              break
      
      cv2.destroyAllWindows()
      

TrackBar 控件

  • createTrackbar:创建TrackBar
    1. trackbarname 控件名称
    2. winname 窗口名称
    3. value 当前值
    4. count 最小值为 0,最大值为count
    5. callback 回调函数
    6. userdata 传递值
  • getTrackbarPos:获取TrackBar的位置
    1. trackbarname 控件名称 输入参数
    2. winname 窗口名称 输入参数
    3. 当前值 输出
      import cv2
      import numpy as np
      
      def callback():
          pass
      
      # 创建窗口
      cv2.namedWindow('trackbar', cv2.WINDOW_NORMAL)
      
      # 创建trackbar
      cv2.createTrackbar('R', 'trackbar', 0, 255, callback)
      cv2.createTrackbar('G', 'trackbar', 0, 255, callback)
      cv2.createTrackbar('B', 'trackbar', 0, 255, callback)
      
      # 创建一个背景图片
      img = np.zeros((480, 640, 3), np.uint8)
      
      while True:
      
          # 获取当前trackbar的值
          r = cv2.getTrackbarPos('R', 'trackbar')
          g = cv2.getTrackbarPos('G', 'trackbar')
          b = cv2.getTrackbarPos('B', 'trackbar')
      
          # 改变背景图片颜色
          img[:] = [b, g, r]
          cv2.imshow('trackbar', img)
      
          key = cv2.waitKey(10)
          if key & 0xFF == ord('q'):
              break
      
      cv2.destroyAllWindows()
      

扩展信息


  1. 如下
    - CAP_ANY = 0, //!< Auto detect == 0
    - CAP_VFW = 200, //!< Video For Windows (obsolete, removed)
    - CAP_V4L = 200, //!< V4L/V4L2 capturing support
    - CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L
    - CAP_FIREWIRE = 300, //!< IEEE 1394 drivers
    - CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
    - CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
    - CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
    - CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE
    - CAP_QT = 500, //!< QuickTime (obsolete, removed)
    - CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed)
    - CAP_DSHOW = 700, //!< DirectShow (via videoInput)
    - CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK
    - CAP_OPENNI = 900, //!< OpenNI (for Kinect)
    - CAP_OPENNI_ASUS = 910, //!< OpenNI (for Asus Xtion)
    - CAP_ANDROID = 1000, //!< Android - not used
    - CAP_XIAPI = 1100, //!< XIMEA Camera API
    - CAP_AVFOUNDATION = 1200, //!< AVFoundation framework for iOS (OS X Lion will have the same API)
    - CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK
    - CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput)
    - CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation
    - CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK)
    - CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC
    - CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect)
    - CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors)
    - CAP_OPENNI2_ASTRA= 1620, //!< OpenNI2 (for Orbbec Astra)
    - CAP_GPHOTO2 = 1700, //!< gPhoto2 connection
    - CAP_GSTREAMER = 1800, //!< GStreamer
    - CAP_FFMPEG = 1900, //!< Open and record video file or stream using the FFMPEG library
    - CAP_IMAGES = 2000, //!< OpenCV Image Sequence (e.g. img_%02d.jpg)
    - CAP_ARAVIS = 2100, //!< Aravis SDK
    - CAP_OPENCV_MJPEG = 2200, //!< Built-in OpenCV MotionJPEG codec
    - CAP_INTEL_MFX = 2300, //!< Intel MediaSDK
    - CAP_XINE = 2400, //!< XINE engine (Linux)
    - CAP_UEYE = 2500, //!< uEye Camera API
    - CAP_OBSENSOR = 2600, //!< For Orbbec 3D-Sensor device/module (Astra+, Femto)
     

  2. 如下
    - EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window.
    - EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed.
    - EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed.
    - EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed.
    - EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released.
    - EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released.
    - EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released.
    - EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked.
    - EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked.
    - EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked.
    - EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively.
    - EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively.
     

  3. 如下
    - EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down.
    - EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down.
    - EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down.
    - EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed.
    - EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed.
    - EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed.