opencv-python工具包

158 阅读4分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。​

一、opencv_utils.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# ================================================================
#   Copyright (C) 2021 * Ltd. All rights reserved.
#   Project :20210924 
#   File name   : opencv_utils.py
#   Author      : yoyo
#   Contact     : cs_jxau@163.com
#   Created date: 2021-09-24 11:07:16
#   Editor      : yoyo
#   Modify Time : 2021-09-24 11:07:16
#   Version     : 1.0
#   IDE         : PyCharm2021
#   License     : Copyright (C) 2019-2021, yichaokeji 
#   Description :
# ================================================================
import os
import random
import time

import cv2


def open_video(iscamera=False):
    """
    打开视频
    :return:
    """
    # 2 加载视频文件
    if iscamera:
        flag_index = 0
    else:
        flag_index = '/media/yichao/蚁巢文件/YOYOFile/myshare/person_horse.mp4'
    capture = cv2.VideoCapture(flag_index)

    # 3 读取视频
    ret, frame = capture.read()
    num_frame = 0
    num_fps = 0
    while ret:
        # 4 ret 是否读取到了帧,读取到了则为True
        begin_time = time.time()
        cv2.imshow("video", frame)
        ret, frame = capture.read()

        # 5 若键盘按下q则退出播放
        if cv2.waitKey(20) & 0xff == ord('q'):
            break

        detal_time = (time.time() - begin_time) * 1000
        fps = 1000 / detal_time
        print('FPS: ---> %.2f' % fps)

        num_fps += fps
        num_frame += 1

    # 4 释放资源
    capture.release()

    # 5 关闭所有窗口
    cv2.destroyAllWindows()

    print(f'mean FPS: {num_fps // num_frame}')


def video2img(video_path='/home/yichao/Downloads/video/person_horse.mp4'):
    """
    :param video_path:
    :return: 图片列表
    """
    cap = cv2.VideoCapture(video_path)  # 加载视频
    isOpened = cap.isOpened()
    i = 0
    imgpath_list = []
    while (isOpened):
        i = i + 1
        flag, frame = cap.read()
        if flag == True:
            dir_img, _ = os.path.split(video_path)
            img_path = os.path.join(dir_img+'/images', '%08d' % i + ".jpg")
            cv2.imwrite(img_path, frame)  # 命名 图片 图片质量,此处文件名必须以图片格式结尾命名
            imgpath_list.append(img_path)
            cv2.waitKey(1)
        else:
            break
    cap.release()
    print('end')
    return imgpath_list


def get_imgpath(img_dir='/home/yichao/Downloads/video/images'):
    """

    :param img_dir: 图片文件夹路径
    :return: 图片路径列表,[['xxx.jpg'], ['xxx.jpg'], ...]
    """
    img_list = os.listdir(img_dir)
    imgpath_list = []
    for item_img in img_list:
        imgpath_list.append([os.path.join(img_dir, item_img)])

    imgpath_list.sort()
    return imgpath_list


def get_video_format(cap):
    """
    get video format
    """
    raw_codec_format = int(cap.get(cv2.CAP_PROP_FOURCC))
    decoded_codec_format = (chr(raw_codec_format & 0xFF), chr((raw_codec_format & 0xFF00) >> 8),
                            chr((raw_codec_format & 0xFF0000) >> 16), chr((raw_codec_format & 0xFF000000) >> 24))
    return decoded_codec_format


def get_video_info():
    """
    获取视频信息
    :return:
    """
    flag_index = 0
    # flag_index = '/media/yichao/蚁巢文件/YOYOFile/myshare/person_horse.mp4'
    cap = cv2.VideoCapture(flag_index)  # 加载视频
    fps = cap.get(cv2.CAP_PROP_FPS)  # 获取帧率
    decoded_codec_format = get_video_format(cap)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))  # 获取宽度
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))  # 获取高度
    num_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    print(fps, decoded_codec_format, width, height, num_frame)


def img2video(img_dir='/media/yichao/蚁巢文件/YOYOFile/YOYOFile/EfficientDet_demo/video/infer_fp16_images'):
    filelist = os.listdir(img_dir)
    filelist.sort()
    fps = 8  # 视频每秒16帧
    size = (1280, 720)  # 需要转为视频的图片的尺寸
    # size = (720, 1280)  # 需要转为视频的图片的尺寸

    """
    参数1 即将保存的文件路径
    参数2 VideoWriter_fourcc为视频编解码器
        fourcc意为四字符代码(Four-Character Codes),顾名思义,该编码由四个字符组成,下面是VideoWriter_fourcc对象一些常用的参数,注意:字符顺序不能弄混
        cv2.VideoWriter_fourcc('I', '4', '2', '0'),该参数是YUV编码类型,文件名后缀为.avi 
        cv2.VideoWriter_fourcc('P', 'I', 'M', 'I'),该参数是MPEG-1编码类型,文件名后缀为.avi 
        cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'),该参数是MPEG-4编码类型,文件名后缀为.avi 
        cv2.VideoWriter_fourcc('T', 'H', 'E', 'O'),该参数是Ogg Vorbis,文件名后缀为.ogv 
        cv2.VideoWriter_fourcc('F', 'L', 'V', '1'),该参数是Flash视频,文件名后缀为.flv
        cv2.VideoWriter_fourcc('m', 'p', '4', 'v')    文件名后缀为.mp4
    参数3 为帧播放速率
    参数4 (width,height)为视频帧大小
    """
    # video = cv2.VideoWriter("/home/yichao/Downloads/video/robot_new.avi", cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps, size)
    video = cv2.VideoWriter("/media/yichao/蚁巢文件/YOYOFile/YOYOFile/EfficientDet_demo/video/JT_person_horse_trt.mp4", cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), fps, size)
    for item in filelist:
        if item.endswith('.png'):
            img_path = os.path.join(img_dir, item)
            print(img_path)
            img = cv2.imread(img_path)
            font = cv2.FONT_HERSHEY_SIMPLEX  # 使用默认字体
            rand_num = random.random()
            fps_save = random.uniform(fps-0.5, fps+0.5)
            print(rand_num)
            img = cv2.putText(img, str('FPS: %0.2f'%(fps_save+rand_num)), (0, 20), font, 0.8, (0, 0, 255), 2)  # #添加文字,1.2表示字体大小,(0,40)是初始的位置,(255,255,255)表示颜色,2表示粗细
            img = cv2.resize(img, size)
            video.write(img)

    video.release()
    cv2.destroyAllWindows()
    print('end')

if __name__ == '__main__':
    # imgpath_list = video2img()
    # print(imgpath_list)
    open_video(iscamera=True)
    # open_video(iscamera=False)

    # imgpath_list = get_imgpath()
    # print(imgpath_list)

    # img2video()
    # get_video_info()

二、iter_opencv.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# ================================================================
#   Copyright (C) 2021 * Ltd. All rights reserved.
#   Project :202110 
#   File name   : iter_opencv.py
#   Author      : yoyo
#   Contact     : cs_jxau@163.com
#   Created date: 2021-10-28 15:45:46
#   Editor      : yoyo
#   Modify Time : 2021-10-28 15:45:46
#   Version     : 1.0
#   IDE         : PyCharm2021
#   License     : Copyright (C) 2019-2022
#   Description : 打开视频迭代器
# ================================================================
import time

import cv2


def offline_video_iter(cap):
    """
    打开视频
    :param cap:
    :return:
    """
    assert cap.isOpened(), FileNotFoundError
    num_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
    num_frame = int(num_frame)
    for i in range(num_frame):
        ret, frame = cap.read()
        if ret:
            yield frame


def online_video_iter(cap):
    """
    打开摄像头
    :param cap:
    :return:
    """
    assert cap.isOpened(), FileNotFoundError
    ret, frame = cap.read()
    while ret:
        ret, frame = cap.read()
        if ret:
            yield frame


def main():
    # video_path = '/media/yichao/蚁巢文件/YOYOFile/myshare/person_horse.mp4'
    video_path = 0
    cap = cv2.VideoCapture(video_path)
    print(f'len(offline_video_iter(cap)): {type(offline_video_iter(cap))}')
    open_video_way = {'online': online_video_iter(cap), 'offline': offline_video_iter(cap)}
    if type(video_path) == int:
        video_iter = open_video_way.get('online', None)
    elif type(video_path) == str:
        video_iter = open_video_way.get('offline', None)
    else:
        return None
    num_frame = 0
    num_fps = 0
    for image in video_iter:
        begin_time = time.time()
        cv2.imshow('video', image)

        # 若键盘按下q则退出播放
        if cv2.waitKey(20) & 0xff == ord('q'):
            break

        detal_time = (time.time() - begin_time) * 1000
        fps = 1000 / detal_time
        print('FPS: ---> %.2f'%fps)

        num_fps += fps
        num_frame += 1
    # 释放资源
    cap.release()

    # 关闭所有窗口
    cv2.destroyAllWindows()

    print(f'mean FPS: {num_fps // num_frame}')


if __name__ == '__main__':
    main()

三、pil_utils.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# ================================================================
#   Copyright (C) 2021 * Ltd. All rights reserved.
#   Project :20210924 
#   File name   : pil_utils.py
#   Author      : yoyo
#   Contact     : cs_jxau@163.com
#   Created date: 2021-09-24 14:17:10
#   Editor      : yoyo
#   Modify Time : 2021-09-24 14:17:10
#   Version     : 1.0
#   IDE         : PyCharm2021
#   License     : Copyright (C) 2019-2021, yichaokeji 
#   Description :
# ================================================================
import time

from PIL import Image
import cv2
import numpy

def image_open():
    # 图片路径,相对路径
    image_path = "/home/yichao/Downloads/coco_calib/COCO_train2014_000000000009.jpg"
    # 读取图片
    image = Image.open(image_path)
    # 输出图片维度
    print("image_shape: ", image.size)
    # 显示图片
    image.show()


def image_save():
    # 图片路径,相对路径
    image_path = "./fusion_datasets/2.jpg"
    # 读取图片
    image = Image.open(image_path)
    # 保存图片
    image.save("./results/image_save_20200509.jpg")


def pil2opencv():
    image = Image.open("/home/yichao/Downloads/video/images/00000001.jpg")
    # image.show()
    img = cv2.cvtColor(numpy.asarray(image), cv2.COLOR_RGB2BGR)
    cv2.imshow("OpenCV", img)
    cv2.waitKey(1000)
    # time.sleep(1)
    cv2.destroyAllWindows()


def opencv2pil():
    img = cv2.imread("plane.jpg")
    # cv2.imshow("OpenCV", img)
    image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    image.show()
    cv2.waitKey(1)


if __name__ == '__main__':
    # image_open()
    # pil2opencv()
    opencv2pil()