我正在Google colab上做一个分类任务。我为任务使用的数据集在谷歌驱动器上,并将文件夹名称作为标签。例如train/cat/img1.jpg, train/dog/img03.jpg
如何从文件夹名称中提取标签?我已经尝试使用下面的代码,但它不能提取文件夹名称。
train_images = []
train_labels = []
for directory_path in glob.glob("/content/drive/My Drive/images/train/*"):
label = directory_path.split("\")[-1]
print(label)
for img_path in glob.glob(os.path.join(directory_path, "*.*")):
print(img_path)
img = cv2.imread(img_path, cv2.IMREAD_COLOR)
img = cv2.resize(img, (SIZE,SIZE))
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
train_images.append(img)
train_labels.append(label)
train_images = np.array(train_images)
train_labels = np.array(train_labels)
既然您知道父文件夹id,您可以使用Files: list来获取以train
为父文件夹的文件列表,使用q
参数:
'q': "'{TRAIN_FOLDER_ID}' in parents"
你只需要修改Google Drive中列出文件的示例,并修改请求:
filenames = drive.ListFile({
'q': "'{TRAIN_FOLDER_ID}' in parents",
'fields': "files(name)"
}).GetList()
参考:- 查找文件和文件夹