python 读图片封装

python 读图片封装 支持 视频,图片文件夹,图片

2024.02.01更新

安装依赖项:pip install natsort

python 复制代码
#-*-coding:utf-8-*-
import os.path
from natsort import natsorted
import cv2

class ImgReader:
    def __init__(self, source, type='mp4'):
        if source.endswith(".mp4"):
            self.type = 'mp4'
            self.cap = cv2.VideoCapture(source)
            if not self.cap.isOpened():
                raise ValueError(f"Error: Could not open video file at {source}")

            self.total_frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
        elif os.path.isfile(source):
            self.type = 'img'
        elif os.path.isdir(source):
            img_files = ['%s/%s' % (i[0].replace("\\", "/"), j) for i in os.walk(source) for j in i[-1] if j.endswith(('jpg', 'png', 'jpeg', 'JPG'))]
            self.img_files= natsorted(img_files)
            self.img_index = 0
            self.type = 'dir_img'
            self.total_frames = len(self.img_files)

        self.source = source

    def get_img(self):
        if self.type == 'mp4':
            ret, frame = self.cap.read()
            if not ret:
                self.cap.release()
                return None
            self.img_index += 1
            return frame,self.img_index,None
        elif self.type == 'img':
            return cv2.imread(self.source),0,None
        elif self.type == 'dir_img':
            if self.img_index < 0 or self.img_index >= len(self.img_files):
                return None
            img_file = self.img_files[self.img_index]

            img = cv2.imread(img_file)
            self.img_index+=1
            return img,self.img_index,img_file
相关推荐
Aspect of twilight12 分钟前
ACM输入输出格式详解
python·acm
见识星球16 分钟前
名企校招攻略
大数据·python
TL滕18 分钟前
从0开始学算法——第四天(题目参考答案)
数据结构·笔记·python·学习·算法
二川bro18 分钟前
循环性能提升:Python向量化计算技巧
开发语言·python
TracyCoder12323 分钟前
大白话讲Java NIO
java·开发语言·nio
potato_may28 分钟前
C++ 发展简史与核心语法入门
开发语言·c++·算法
m5655bj33 分钟前
通过 C# 将 RTF 文档转换为图片
开发语言·c#
rabbit_pro1 小时前
Java 文件上传到服务器本地存储
java·服务器·python
5***g2981 小时前
Windows安装Rust环境(详细教程)
开发语言·windows·rust