Skip to content

opencv图像视频基本操作


图像操作:

图像读取显示并保存

tips:opencv中读取的图像颜色通道默认BGR排列

import cv2

def main():
    img = cv2.imread('source/lena.jpg')
    if img is not None:
        cv2.imshow("IMG",img)
        cv2.waitKey(0)
        cv2.imwrite('./source/output/lena.jpg',img)
    else :
        print('read false')
        exec()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    main()

图像灰度处理

tips:用cv2.cvtClor()函数实现图像转灰度操作

demo.py
import cv2
import numpy as np

def main():
    cap = cv2.VideoCapture(0)
    while cap.isOpened() :
        ret,frame = cap.read()
        if ret is False :
            print('ret is false')
            break;
        frame = cv2.cvtColor(frame ,cv2.COLOR_BGR2GRAY)
        cv2.imshow("FRAME", frame)
        if cv2.waitKey(20) == ord('q'):
            print('closed')
            cap.release()
            cv2.destroyAllWindows()
            exit()
    print('vedio has been closed')

if __name__ == '__main__':
    main()

视频操作:

视频读取显示并保存

graph LR
Z[START]-->
A(读取视频)-->B(获取视频信息)
C[宽高FPS]-->B
B-->D(获取或指定视频编码信息)
D-->E(创建视频写入对象)
F[输出路径]-->|传参|E
G[视频编码]-->|传参|E
B-->|传参|E
E-->H(写入视频)-->I[END]

tips:写入视频的视频编码可获取传入视频流的也可以用cv2.VideoWriter_fourcc()函数手动指定

VideoWriter_fourcc()函数参数:

*'mp4v' [MPEG-4编码]

*'XVID' [XVID (AVI容器常用)]

import cv2
import numpy as np

source_path = 'source/test.mp4'
output_path = './source/output/gray_test.mp4'

def main():
    cap = cv2.VideoCapture(source_path)
    if cap.isOpened() is False:
        print('can\'t open cap')
        exit()
    # 获取宽高和FPS
    frame_W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    FPS = int(cap.get(cv2.CAP_PROP_FPS))
    # 获取视频编码
    fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
    # 创建视频写入对象
    frame_writer = cv2.VideoWriter(output_path,fourcc,FPS,(frame_W,frame_h))
    size = (int(frame_W/4),int(frame_h/4))
    while cap.isOpened() :
        ret,frame = cap.read()
        if ret:
            frame = cv2.resize(frame,size)
            cv2.imshow('raw',frame)
            frame = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
            frame_writer.write(frame)
            cv2.imshow('gray',frame)
            if int(cv2.waitKey(20)) == int(ord('q')):
                break 
        else:
            print(f"ret:{ret}")
            break

    # 释放资源
    frame_writer.release()
    cap.release()
    cv2.destroyAllWindows()
    print('run over !')

if __name__ == '__main__':
    main()