读取图片

1
2
3
import/export cv2

cv2import.imread('demo.png', )

读取视频

GUI 功能

图片基本操作

  1. 教程
  2. 基本操作示例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    import/export numpy as np
    import/export cv2
    
    img = cv2.imread('messi5.jpg',0)
    cv2import.imshow('image',img)
    k = cv2.waitKey(0)
    if k == 27:         # wait for ESC key to exit
        cv2import.destroyAllWindows()
    elif k == ord('s'): # wait for 's' key to save and exit
        cv2import.imwrite('messigray.png',img)
        cv2import.destroyAllWindows()
  3. 图像转换示例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    import/export cv2
    import/export numpy as np
    import/export matplotlib.pyplot as plt
    
    img = cv2.imread('messi4.jpg')
    b,g,r = cv2.split(img)
    img2 = cv2.merge([r,g,b])
    plt.subplot(121);plt.imshow(img) # expects distorted color
    plt.subplot(122);plt.imshow(img2) # expect true color
    plt.show()
    
    cv2import.imshow('bgr image',img) # expects true color
    cv2import.imshow('rgb image',img2) # expects distorted color
    cv2.waitKey(0)
    cv2.destroyAllWindows()

大家的讨论

链接:

读取

  • cv2.imread

    • flag 参数

      • cv2.IMREAD_COLOR –> 1
      • cv2.IMREAD_GRAYSCALE –> 0
      • 注意:

        1. 这些参数都是以 cv2.IMREAD_ 开头
        2. 直接 google opencv imread 可以查找相关解释

创建显示窗格

  • cv2.namedWindow

显示

  • cv2.imshow

退出 与 捕获按键

  • cv2.waitKey

销毁窗格

  • cv2.destroyAllWindows

保存

  • cv2.imwrite

格式转换

  • cv2.cvtColor

    • flag 参数

      • 以 cv2.COLOR_ 开头

        • cv2.COLOR_BGR2RGB
        • cv2.COLOR_BGR2GRAY

chanel 切分

  • cv2.split –> b, g, r

chanel 合并

  • cv2.merge

使用 Matplotlib

显示 plt.imshow
1
2
3
4
5
6
7
8
import/export numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('messi5.jpg',0)
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([])  # to hide tick values on X and Y axis
plt.show()

使用 numpy

  • 与 cv2 一起使用
创建多通道图像
1
2
import numpy as np
img = np.zeros([512, 512, 3])
  • 形状参数

    • shape –> [512, 512, 3]

      • [row, column, layer]
      • [height, width, channel(通道数)]
提取单个像素
1
2
3
blue = img[x, y, 0]
green = img[x, y, 1]
red = img[x, y, 2]
合成多通道图像
1
2
3
4
5
6
BlueConsole-SPP-1 = img[x, y, 0]
green = img[x, y, 1]
red = img[x, y, 2]
ourImag = np.zeros([512, 512, 3])

ourImag[:] = [blue, green red]

视频基本操作

读取

  • cv2.VideoCapture

    • 返回的是一个图像读取器
    • 参数

      • 摄象头序号 或者 视频文件
  • 示例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    import/export numpy as np
    import cv2
    
    cap = cv2.VideoCapture(0)
    
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
    
        # Our operations on the frame come here
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        # Display the resulting frame
        cv2.imshow('frame',gray)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()
读取图片
  • cap.read
读取器销毁
  • cap.release
读取器– 判断正常打开
  • cap.isOpened()
读取器--获取视频属性
  • cap.get(propId)

    • 参数 propId

      1. 数值 0~18

        • 每个值,对应特别的属性
        • 3: –> width
        • 4: –> hight
      2. eg:

        • cv2.CAP_PROP_WIDTH –> 3
        • cv2.CAP_PROP_HEIGHT –> 4
      3. 以 cv2.CAP_PROP_ 开头
读取器--设置视频属性
  • cap.set(propId, value)

    • But I want to modify it to 320x240. Just use ret = cap.set(3,320) and ret = cap.set(4,240)
    • 注意

      • 对于 width x height

        • 输入可以任意输入设定值
        • 但是最后有效还要看摄像头(设备)是否支持
        • 它会自动选定一组合适的,且最接近的可选值

播放视频

  • 方法

    • 不断显示(循环刷新)图片

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      
      import/export numpy as np
      import cv2
      
      cap = cv2.VideoCapture('vtest.avi')
      
      while(cap.isOpened()):
          ret, frame = cap.read()
      
          gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
      
          cv2.imshow('frame',gray)
          if cv2.waitKey(1) & 0xFF == ord('q'):
              break
      
      cap.release()
      cv2.destroyAllWindows()

保存视频

  • cv2.VideoWriter 对象

    • 这是一个类
    • 使用步骤

      1. 指定保存路径
      2. 创建编码工具 cv2.VideoWriter_ 开头类

        • eg: cv2.VideoWriter_fourcc(*'MJPG')

          • 解说:FourCC 是一种视频编码格式 codec
  • 示例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    
    import numpy as np
    import cv2
    
    cap = cv2.VideoCapture(0)
    
    # Define the codec and create VideoWriter object
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
    
    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            frame = cv2.flip(frame,0)
    
            # write the flipped frame
            out.write(frame)
    
            cv2.imshow('frame',frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            break
    
    # Release everything if job is finished
    cap.release()
    out.release()
    cv2.destroyAllWindows()

绘图工具函数

线 cv2.line

带箭头线 cv2.arrowedLine

圆 cv2.circle

矩形 cv2.rectangle

椭圆 cv2.ellipse

多边形 cv2.polylines

  • 注意是封闭多线段

    1
    2
    3
    
    pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
    pts = pts.reshape((-1,1,2))
    cv.polylines(img,[pts],True,(0,255,255))
    • 第三个参数 True, 指定封闭路径

文本 cv2.putText

  • 注意

    • 需要指定 fontFace 参数,即字体

      • eg: cv2.FONT_HERSHEY_SIMPLEX
      • 以 cv2.FONT_ 开头

        1
        2
        
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, 'Opencv test', (10, 500), font, (255, 0, 0), 10, cv2.LINE_AA)

用到的参数

输入图片 img
绘制颜色 color
  • 注意:bgr 格式
  • eg: (255, 0, 0) –> 蓝色
厚度 thickness
  • 整数类型
  • 默认值:1
  • 特殊值:-1

    • 填充颜色,如对于圆
线型

鼠标事件

参考:

鼠标事件值

  • 以 cv2.EVENT_ 开头

    • cv2.EVENT_FLAG_RBUTTON
    • cv2.EVENT_LBUTTONDOWN

      1
      2
      3
      
      >>> import cv2
      >>> events = [i for i in dir(cv2) if 'EVENT' in i]
      >>> print events

事件处理:回调函数形式

  • 注意

    • 回调函数的接口

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      
      import cv2
      import numpy as np
      
      # mouse callback function
      def draw_circle(event,x,y,flags,param):
          if event == cv2.EVENT_LBUTTONDBLCLK:
              cv2.circle(img,(x,y),100,(255,0,0),-1)
      
      # Create a black image, a window and bind the function to window
      img = np.zeros((512,512,3), np.uint8)
      cv2.namedWindow('image')
      cv2.setMouseCallback('image',draw_circle)
      
      while(1):
          cv2.imshow('image',img)
          if cv2.waitKey(20) & 0xFF == 27:
              break
      cv2.destroyAllWindows()
调用回调函数 cv2.setMouseCallback(imag, mouse_event_callback)
def event_callback(event, x, y, flags, param)

TrackBar 工具

教程:

  1. 创建

    1
    
    cv2.createTrackBar("barName", "boundingWindow", 0, 255, callback_fun)
  2. 获取已经创建的 TrackBar 的 值

    1
    
    value = cv2.getTrackBar("barName", "boundingWindow")
  3. 实例

HSV(Hue, Saturation, Value)