keras语义分割--准备分割数据集--方式1

tech2025-06-18  1

准备原图像及其标签的路径

import os # 定义原图像所在的目录dir,及路径path imgs_dir = r"The Oxford-IIIT Pet Dataset\images" imgs_path = [] for fname in os.listdir(imgs_dir): if fname.endswith('.jpg') and not fname.startswith('.'): imgs_path.append(os.path.join(imgs_dir, fname)) # 定义原图像标签所在的目录dir,及路径path labels_dir = r"The Oxford-IIIT Pet Dataset\annotations\trimaps" labels_path = [] for fname in os.listdir(labels_dir): if fname.endswith('.png') and not fname.startswith('.'): labels_path.append(os.path.join(labels_dir, fname)) # 打印原图像路径及标签路径 for img_path, label_path in zip(imgs_path, labels_path): print(img_path, '|', label_path, '\n') # 对原图像路径及标签路径进行排序 imgs_path = sorted(imgs_path) labels_path = sorted(labels_path) # 打印排序后的原图像路径及标签路径 for img_path, label_path in zip(imgs_path, labels_path): print(img_path, '|', label_path, '\n') # 由上可以发现,os.listdir()返回的路径是随机的、无序的,由于原图像及标签需要一一对应。 # 因此,需要对它们的路径进行排序

第一次打印 第二次打印

上述代码还可简化为:

import os def acquireDataPath(data_dir, suffix): data_path = sorted([ os.path.join(data_dir, fname) for fname in os.listdir(data_dir) if fname.endswith(suffix) and not fname.startswith('.') ]) return data_path imgs_path = acquireDataPath(r"The Oxford-IIIT Pet Dataset\images", 'jpg') labels_path = acquireDataPath(r"The Oxford-IIIT Pet Dataset\annotations\trimaps", 'png') for img_path, label_path in zip(imgs_path, labels_path): print(img_path, '|', label_path, '\n')

注: 在这句代码中if fname.endswith(suffix) and not fname.startswith('.'),一定要说明图像名的后缀是什么,以及不要以什么前缀开头。 具体怎么跑模型参考链接: https://keras.io/examples/vision/oxford_pets_image_segmentation/

最新回复(0)