OpenCV 入门 - 安装、读写文件

OpenCV 入门 - 读写文件

1. 安装

pip install opencv-python

2. 读写图片

2.1 读取cv2.imread()

img = cv2.imread('test.png', 1)
  • The second Parameter:

    1: cv2.IMREAD_COLOR, default, 彩色,忽略alpha通道。return 3d-array, shape of (h,w,c), channel: B, G, R

    0,2: cv2.IMREAD_GRAYSCALE, 灰色。return 2d-array, shape of (h,w)

    -1 : cv2.IMREAD_UNCHANGED, 保留alpha通道。return 3d-array, shape of (h,w,c), channel: B, G, R, Alpha

    where h, w, c represent height, width, channel respectively. all elements of img is in the range of \([0, 255]\).

  • Return:

    type of numpy.ndarray, every elements is the type of numpy.uint8

2.2 显示 cv2.imshow()

cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.imshow('image', img)
cv2.waitKey(0)
# 等待指定的毫秒数后,是否按下键盘的某个键
# 0 无线等待
cv2.destroyAllWindows()
  • Second parameter of cv2.namedWindow()

    cv2.WINDOW_AUTOSIZE: default, 窗口大小不可以改变

    cv2.WINDOW_NORMAL: 窗口大小可以改变

    cv2.WINDOW_FREERATIO: 窗口大小自适应比例

    cv2.WINDOW_KEEPRATIO: 窗口大小保持比例

2.3 写入 cv2.imwrite()

cv2.imwrite('test_new.png', img)

3. 图片编辑

3.1 添加元素:线、矩形、圆、椭圆、箭头、多边形

  • 通用参数:

    • image: 图片对象

    • pt1 and pt2: 均为二元 tuple,每个元素必须为 np.int32 类型,起终点坐标

    • color: 二元 tuple,RGB 颜色

    • thickness: int,边框粗细,单位为像素(pixel)。-1 表示填充整个图形

    • lineType: 线类型,一般设为 cv2.LINE_AA抗锯齿,看起来会非常平滑

    • shift:坐标 pt1pt2中的小数位数。无论 shift 设为多少, pt1pt2 的数值必须保持整数,不知道为什么

  • 返回值:此类函数会在原图像上直接操作,返回与不返回的结果是一样的,如

    # img, img1, img2 都一样
    img1 = img.copy()
    cv2.line(img, (500, 500), (200, 100), (0, 0, 255))
    img2 = cv2.line(img1, (500, 500), (200, 100), (0, 0, 255))
    
  1. 线 cv2.line()

    cv2.line(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)
    
  2. 矩形 cv2.rectangle()

    cv2.rectangle(img, pt1, pt2, color, thickness=None, lineType=None, shift=None)
    
  3. cv2.circle()

    cv2.circle(img, center, radius, color, thickness=None, lineType=None, shift=None)
    
    • center:二元 tuple,圆坐标

    • radiu: 半径

  4. 椭圆 cv2.ellipse()

    cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=None, lineType=None, shift=None)
    
    • axes: 二值 tuple,表示长轴和短轴

    • angle: 椭圆旋转角度,单位为度(0 ~ 360)

    • startAngle: 椭圆弧的起始角度,单位为度(0 ~ 360)

    • endAngle: 椭圆弧的终止角度,单位为度(0 ~ 360)

  5. 箭头 cv2.arrowedLine()

    cv2.arrowedLine(img, pt1, pt2, color, thickness=None, line_type=None, shift=None, tipLength=None)
    
    • tipLength: 箭头尖端相对于整个箭头长度的长度 (一般为 0 ~ 1之间,也可以大于1)
  6. 多边形 cv2.polylines()

    cv2.polylines(img, pts, isClosed, color, thickness=None, lineType=None, shift=None)
    
    • pts: 点集,n*2 的 np.ndarray,每个元素必须为 np.int32 类型

    • isClosed: bool 类型,图形是否闭合

3.3 添加文字 cv2.putText()

cv2.putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)

3.2 添加时间

milliseconds 转为时间字符串函数:

# milliseconds to time string
def Msecs2Timestr(milliseconds):
    milliseconds = int(milliseconds)
    seconds = milliseconds // 1000
    milliseconds = milliseconds % 1000
    minutes = 0
    hours = 0
    if seconds >= 60:
        minutes = seconds // 60
        seconds = seconds % 60
    if minutes >= 60:
        hours = minutes // 60
        minutes = minutes % 60
    time_str = '{0:0>2d}:{1:0>2d}:{2:0>2d}:{3:0>3d}'.format(hours, minutes, seconds, milliseconds)
    return time_str

4. 读写视频

4.1 读取视频 cv2.VideoCapture()

注意:OpenCV 读取的视频没有音轨。

import cv2
# 读取视频
video_path = "Study1.mp4"
cap = cv2.VideoCapture(video_path)
  • cv2.VideoCapture()

    • parameter:

      • 0: default,调用摄像头
    • The return of cap.read():

      • ret: bool, whether frame is available

      • frame: type of numpy.ndarray, every elements is the type np.unit8

    • 常用属性

      • cap.isOpened(), bool, 初始化是否成功

      • video_fps = cap.get(cv2.CAP_PROP_FPS), 帧率

        video_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

        video_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

        video_msec = cap.get(cv2.CAP_PROP_POS_MSEC),视频当前的位置(毫秒)

        video_frames = cap.get(cv2.CAP_PROP_POS_FRAMES),视频当前的位置(帧数)

4.2 播放视频

while True:
    ret, frame = cap.read() # Capture frame-by-frame
    cv2.imshow('frame', frame) # Display the resulting frame
    if cv2.waitKey(1) & 0xFF == 27: # 按“ESC”退出
    # cv2.waitKey(1) & 0xFF == ord('q') # 按“q”键退出
        break
cap.release()
cv2.destroyAllWindows()

3.3 逐帧遍历

ret = True
while ret:
    ret, frame = cap.read() # Capture frame-by-frame
    pass
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        pass

4.4 保存视频

fourcc = cv2.VideoWriter_fourcc(*'MP4V')  # 视频编解码器
out = cv2.VideoWriter(".Study1-1.mp4", fourcc, video_fps, (int(video_width), int(video_height)))
# 逐帧添加
out.write(frame)
out.release()

4. 鼠标交互

cv2.setMouseCallback()

  • window name
  • func: 自定义函数
  • param: 初入func的额外参数
cv2.namedWindow('image')
cv2.setMouseCallback('image', func, param)

func函数:

  • Parameters:

    • event: 鼠标事件
    • x, y: 鼠标坐标
    • flags: 当前鼠标状态
    • param: 额外参数
  • event可选事件

    • 滑动 cv2.EVENT_MOUSEMOVE or 0
    • 左键点击 cv2.EVENT_LBUTTONDOWN or 1
    • 右键点击 cv2.EVENT_RBUTTONDOWN or 2
    • 中键点击 cv2.EVENT_MBUTTONDOWN or 3
    • 左键放开 cv2.EVENT_LBUTTONUP or 4
    • 右键放开 cv2.EVENT_RBUTTONUP or 5
    • 中键放开 cv2.EVENT_MBUTTONUP or 6
    • 左键双击 cv2.EVENT_LBUTTONDBLCLK or 7
    • 右键双击 cv2.EVENT_RBUTTONDBLCLK or 8
  • flags代表鼠标的拖拽事件,以及键盘鼠标联合事件,共有32种事件:

    • 左鍵拖曳 EVENT_FLAG_LBUTTONor 1
    • 右鍵拖曳 EVENT_FLAG_RBUTTON or 2
    • 中鍵拖曳 EVENT_FLAG_MBUTTON or 4
    • 按Ctrl不放事件 EVENT_FLAG_CTRLKEY or 8
    • 按Shift不放事件 EVENT_FLAG_SHIFTKEY or 16
    • 按Alt不放事件 EVENT_FLAG_ALTKEY or 32
posted @ 2022-02-11 16:53  veager  阅读(101)  评论(0)    收藏  举报