首页 > 解决方案 > 检查文件夹图像的扩展类型并确保所有图像都是一种格式

问题描述

我正在做一个与计算机视觉相关的项目。由于我总是喜欢编写简洁的代码(即使我没有接受过正式的编码培训),所以我不得不在这里提出一些问题。请多多包涵。

我想通过以下功能实现一些目标。

一是它检查扩展类型,并确保它们是 jpg、jpeg 或 png(但此列表是可定制的)。

二是它检查图像文件夹并确保它们都是相同的扩展类型,没有什么奇怪的,比如 100 张带有“.jpg”的图像,而其余的都是“.png”。

最后,函数最终应该返回扩展类型,这样我就可以在我的管道中做这样的事情:

image_path = os.path.join(path_to_image, image_id+check_file_type(image_folder_path))

PS:有什么方法可以不使用 + 运算符来连接两个字符串,它看起来真的很丑(但这只是我的小毛病)。

我的功能如下,我总觉得它有问题,虽然它似乎工作正常,但我希望有经验的人纠正/改进我的功能,而不是看起来很麻烦。

from collections import Counter
from tqdm import tqdm
from type import Optional, List

def check_file_type(image_folder_path, allowed_extensions:Optional[List]=None):
    if allowed_extensions is None:
        allowed_extensions = ['.jpg', '.png', '.jpeg']

    extension_type = []
    file_list = os.listdir(image_folder_path)
    for file in tqdm(file_list):
        extension_type.append(os.path.splitext(file)[-1].lower())
    
    extension_dict = Counter(extension_type)
    assert len(extension_dict.keys()) == 1, "The extension in the folder should all be the same, but found {} extensions".format(extension_dict.keys)
    extension_type = list(extension_dict.keys())[0]
    assert extension_type in allowed_extensions
    return extension_type

标签: pythonpython-3.x

解决方案


如果您不想使用集合并且不想遍历文件夹中的每个文件,那么您可以执行类似的操作。

import glob

def check_file_type(image_folder_path, allowed_extensions=None):
    if allowed_extensions is None:
        allowed_extensions = ['.jpg', '.png', '.jpeg']

    no_files_in_folder = len(glob.glob(image_folder_path+"/*")) 
    extension_type = ""
    no_files_allowed = 0

    for ext in allowed_extensions:
      no_files_allowed = len(glob.glob(image_folder_path+"/*"+ext))
      if no_files_allowed > 0:
        extension_type = ext
        break

    assert no_files_in_folder == no_files_allowed, "The extension in the folder should all be the same, but found more than one extensions"
    return extension_type

首先获取文件夹中的文件总数

然后获取每个允许的扩展名的文件数,如果 glob 为一个扩展名获取多个文件,则循环将中断并断言将检查 no_files_in_folder == no_files_allowed

如果为 true,它将返回扩展类型

如果为假,那么该文件夹中肯定有多个扩展名的文件


推荐阅读