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
相关推荐
CodeWithMe4 分钟前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
蓝婷儿13 分钟前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
蜉蝣之翼❉16 分钟前
opencv如何在仿射变换后保留完整图像内容并自动裁剪
opencv·计算机视觉
Mikhail_G37 分钟前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析
YuTaoShao42 分钟前
Java八股文——集合「List篇」
java·开发语言·list
hello kitty w1 小时前
Python学习(7) ----- Python起源
linux·python·学习
Bl_a_ck1 小时前
【JS进阶】ES6 实现继承的方式
开发语言·前端·javascript
站大爷IP1 小时前
Python文本序列的类型
python
愈努力俞幸运2 小时前
c++ 头文件
开发语言·c++
千千寰宇2 小时前
[Java/Python] Java 基于命令行调用 Python
python·java se-jdk/jvm