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
相关推荐
wjs20243 分钟前
Go 语言类型转换
开发语言
菩提祖师_4 分钟前
基于Java的物联网智能交通灯控制系统
java·开发语言·物联网
技术工小李7 分钟前
2026马年年会“接福袋”游戏
python
公众号:ITIL之家9 分钟前
服务价值体系重构:在变化中寻找不变的运维本质
java·运维·开发语言·数据库·重构
zhaokuner15 分钟前
01-领域与问题空间-DDD领域驱动设计
java·开发语言·设计模式·架构
0思必得017 分钟前
[Web自动化] Requests模块请求参数
运维·前端·python·自动化·html
青岛少儿编程-王老师23 分钟前
CCF编程能力等级认证GESP—C++8级—20251227
java·开发语言·c++
charlie11451419127 分钟前
FreeRTOS:中断(ISR)与 RTOS 安全 API
开发语言·c·freertos·实时操作系统
计算机毕设指导627 分钟前
基于微信小程序的个性化漫画阅读推荐系统【源码文末联系】
java·python·微信小程序·小程序·tomcat·maven·intellij-idea
百锦再27 分钟前
开发抖音小程序组件大全概述
人工智能·python·ai·小程序·aigc·notepad++·自然语言