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
相关推荐
川石课堂软件测试1 分钟前
零基础小白如何学习自动化测试
python·功能测试·学习·测试工具·jmeter·压力测试·harmonyos
Evand J3 分钟前
【MATLAB例程】VSIMM与IMM在机动目标跟踪中的性能对比,CV+CT双模型
开发语言·matlab·目标跟踪
Meteors.7 分钟前
Kotlin协程序使用技巧和应用场景
android·开发语言·kotlin
在繁华处8 分钟前
Java从零到熟练(十二):Java与AI工具整合
java·人工智能·python
晚风吹红霞11 分钟前
C++ vector 深度剖析:从入门到模拟实现,避开所有坑
开发语言·c++
如烟花的信页12 分钟前
数美滑块逆向分析
javascript·爬虫·python·js逆向
凯瑟琳.奥古斯特13 分钟前
力扣1235完整解法详解
java·开发语言·leetcode
z落落19 分钟前
C# 继承基础详解(代码实战+权限规则)
java·开发语言
techdashen19 分钟前
你想在 Rust 中实现动态库热重载?
开发语言·chrome·rust
不会C语言的男孩20 分钟前
C++ Primer 第5章:语句
开发语言·c++