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
相关推荐
yong99903 分钟前
基于MATLAB的随机振动界面设计与功率谱密度分析实现
开发语言·matlab
摸鱼仙人~12 分钟前
一文详解PyTorch DDP
人工智能·pytorch·python
超级种码12 分钟前
Java:JavaAgent技术(java.instrument和java.attach)
java·开发语言·python
天天向上102414 分钟前
go 配置热更新
开发语言·后端·golang
晨晖229 分钟前
顺序查找:c语言
c语言·开发语言·算法
wadesir38 分钟前
C++非对称加密实战指南(从零开始掌握RSA加密算法)
开发语言·c++
Salt_07281 小时前
DAY44 简单 CNN
python·深度学习·神经网络·算法·机器学习·计算机视觉·cnn
Iridescent11211 小时前
Iridescent:Day35
python
a程序小傲1 小时前
阿里Java面试被问:.Java 8中Stream API的常用操作和性能考量
开发语言·windows·python
爱装代码的小瓶子2 小时前
【c++进阶】从C++98到C++11的奇妙旅程(故事科普版)
开发语言·c++