deffind_classes(dir):# 得到指定目录下的所有文件,并将其名字和指定目录的路径合并# 以数组的形式存在classes中
classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
# 使用sort()进行简单的排序
classes.sort()
# 将其保存的路径排序后简单地映射到 0 ~ [ len(classes)-1] 的数字上
class_to_idx = {classes[i]: i for i in range(len(classes))}
# 返回存放路径的数组和存放其映射后的序号的数组return classes, class_to_idx
2. has_file_allowed_extension
defhas_file_allowed_extension(filename, extensions):"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""# 将文件的名变成小写
filename_lower = filename.lower()
# endswith() 方法用于判断字符串是否以指定后缀结尾# 如果以指定后缀结尾返回True,否则返回Falsereturn any(filename_lower.endswith(ext) for ext in extensions)
3. make_dataset
defmake_dataset(dir, class_to_idx, extensions):
images = []
# expanduser把path中包含的"~"和"~user"转换成用户目录# 主要还是在Linux之类的系统中使用,在不包含"~"和"~user"时# dir不变
dir = os.path.expanduser(dir)
# 排序后按顺序通过for循环dir路径下的所有文件名for target in sorted(os.listdir(dir)):
# 将路径拼合
d = os.path.join(dir, target)
# 如果拼接后不是文件目录,则跳出这次循环if