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
相关推荐
小辉同志6 分钟前
208. 实现 Trie (前缀树)
开发语言·c++·leetcode·图论
A-刘晨阳6 分钟前
当数据学会“秒回“:工业4.0时代的实时计算革命
开发语言·数据库·perl
沐知全栈开发7 分钟前
Lua 基本语法
开发语言
Where-8 分钟前
LangChain、LangGraph入门
python·langchain·langgraph
极光代码工作室10 分钟前
基于机器学习的垃圾短信识别系统
人工智能·python·深度学习·机器学习
小李子呢021112 分钟前
前端八股JS---ES6新增内容
开发语言·javascript·ecmascript
yaoxin52112316 分钟前
381. Java IO API - 控制文件树遍历流程
java·开发语言
2201_7568473318 分钟前
如何设置备库只接日志不应用_暂停MRP且维持网络传输的方法
jvm·数据库·python
zhaoshuzhaoshu20 分钟前
Python 语法之控制结构详解
开发语言·python
咚为22 分钟前
深入理解 Rust 的静态分发与动态分发:从 `impl Trait` 到 `dyn Trait`
开发语言·后端·rust