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
相关推荐
yudiandian201414 分钟前
02 Oracle JDK 下载及配置(解压缩版)
java·开发语言
要加油哦~20 分钟前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式
B站_计算机毕业设计之家22 分钟前
计算机毕业设计:Python农业数据可视化分析系统 气象数据 农业生产 粮食数据 播种数据 爬虫 Django框架 天气数据 降水量(源码+文档)✅
大数据·爬虫·python·机器学习·信息可视化·课程设计·农业
Q_Q51100828535 分钟前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
鄃鳕37 分钟前
python迭代器解包【python】
开发语言·python
new coder38 分钟前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
应用市场40 分钟前
OpenCV编程入门:从零开始的计算机视觉之旅
人工智能·opencv·计算机视觉
驰羽44 分钟前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
Narcissiffo1 小时前
【C语言】str系列函数
c语言·开发语言
workflower1 小时前
软件工程与计算机科学的关系
开发语言·软件工程·团队开发·需求分析·个人开发·结对编程