opencv读取视频并保存图像的方法

问题重述

​ 实习项目要做安全帽目标检测,拿到了公司给的一些视频数据,使用Opencv读取视频并每隔 1 s 1s 1s存储一副图像,下面是一些视频数据

opencv读取视频并保存图像的方法

实现步骤 添加依赖库

import cv2
import os

定义视频路径和图像存储路径

video_path = \'./未戴安全帽视频01/\'
image_path = \'./images/\'

读取视频文件

video_files = [i for i in os.listdir(video_path) if i.split(\'.\')[-1] in [\'mp4\']]
len(video_files)

获取视频帧

# video_file:\'./未戴安全帽视频01/中建四局-东围墙5_001_2021-03-22-18-04-28_2021-03-22-18-04-33.mp4\', 
# pic_dir:\'中建四局-东围墙5_001_2021-03-22-18-04-28_2021-03-22-18-04-33\'
def get_image(video_file, pic_dir):
    if not os.path.exists(pic_dir):
        os.makedirs(pic_dir)
    
    # cv2读取视频文件
    vc = cv2.VideoCapture(video_file)
    index = 0
    # 判断载入的视频是否可以打开
    rval = vc.isOpened()
    while rval:  # 循环读取视频帧
        index = index + 1
        
        rval, frame = vc.read()
        # 每十帧保存一张图片
        if index * 10 % 1 == 0:
            if rval:
                # cv2.imshow(\"capture\", frame)
                save_file = pic_dir + str(index).zfill(5) + \'.png\'
                cv2.imwrite(save_file, frame)  # 存储为图像,保存名为文件夹名
                cv2.waitKey(1)
            else:
                break
        vc.release()
    print(\"已保存%d\" %(index - 1) + \"张图片\")
        
# video_file = \'./未戴安全帽视频01/01.mp4\'
# pic_path = \'01/\'
# get_image(video_file, image_path + pic_path)

遍历视频文件

for file in video_files:
    video_file = video_path + file
    pic_path = image_path + file.replace(\'.mp4\', \'/\')
    get_image(video_file, pic_path)

已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片
已保存1张图片

完整代码

import cv2
import os


def save_img():
    video_path = r\'F:\\test\\3.10\'
    videos = os.listdir(video_path)
    for video_name in videos:
        file_name = video_name.split(\'.\')[0]
        folder_name = video_path +\'_\'+ file_name
        os.makedirs(folder_name, exist_ok=True)
        print(video_path + \'/\' + video_name)
        vc = cv2.VideoCapture(video_path + \'/\' + video_name)
        # 读入视频文件
        c = 0
        rval = vc.isOpened()

        while rval:  # 循环读取视频帧
            c = c + 1

            rval, frame = vc.read()
            if c%10 ==0:
                pic_path = folder_name + \'/\'
                if rval:
                    cv2.imwrite(pic_path + str(c) + \'.png\', frame)  # 存储为图像,保存名为文件夹名
                    cv2.waitKey(1)
                else:
                    break
        vc.release()
        print(\'save_success\')
        print(folder_name)


save_img()

存在问题

读取路径问题

问题:读取视频结果显示没有打开视频,检查发现视频路径错误,导致没有正确打开

解决:可以在读取之前检查路径,即判断要保存的文件夹是否存在,不存在就创建该文件夹。代码如下:

if not os.path.exists(path):
    os.makedirs(path)

中文路径问题

问题:cv2.imwrite()保存图像路径不能存在中文字符,否则无法保存,并且没有任何提示!!!

解决:改为英文路径即可。

最终结果

opencv读取视频并保存图像的方法

opencv读取视频并保存图像的方法

到此这篇关于opencv读取视频并保存图像的方法的文章就介绍到这了,更多相关opencv读取视频内容请搜索免费资源网以前的文章或继续浏览下面的相关文章希望大家以后多多支持免费资源网!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容