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
相关推荐
脏脏a1 分钟前
类与对象(上):面向过程到面向对象的跨越,类的定义、封装与 this 指针等核心概念深度剖析
开发语言·c++
淡忘_cx7 分钟前
Dify Plugin 开发教程
python
熊猫比分站20 分钟前
[特殊字符] Java/Vue 实现体育比分直播系统,支持多端实时更新
java·开发语言·vue.js
海琴烟Sunshine26 分钟前
leetcode 338. 比特位计数 python
python·算法·leetcode
inferno44 分钟前
Maven基础(一)
java·开发语言·maven
csbysj20201 小时前
SQLite Truncate Table: 完全删除表中的数据
开发语言
呆萌很1 小时前
字典推导式练习题
python
tung tung tung sahur1 小时前
领略 Rust 抽象之美:自定义迭代器实现全解析
开发语言·后端·rust
ftpeak1 小时前
《Rust MP4视频技术开发》第八章:生成MP4
开发语言·rust·音视频·mp4
闲人编程2 小时前
Python在云计算中的应用:AWS Lambda函数实战
服务器·python·云计算·aws·lambda·毕设·codecapsule