![](/img/trans.png)
[英]how to move multiple images from a folder to another folder in python?
[英]How to create a for loop to extract specific images from a folder to another folder?
我在名為 sample_labels.csv 的 csv 文件中有這個表,在表中有圖像索引和 class 標簽 -
圖像索引 | 標簽 |
---|---|
00000013_005.png | 肺氣腫 |
00000013_026.png | 肺氣腫 |
00000017_001.png | 沒有發現 |
00000042_002.png | 沒有發現 |
00000084_000.png | 積液 |
00000099_003.png | 積液 |
我有另一個文件夾,其中包含圖像。 該文件夾名為“train_images”
如何創建一個 for 循環,創建名為“Emphysima”、“No find”、“Effusion”的文件夾,並將這些圖像與相應的 label 存儲在相應的文件夾中?
我的意思是“Emphysima”文件夾中帶有 Emphysima label 的兩張圖像等等。
如果我理解您的要求,您可以通過以下方式之一執行此操作:
數據
import pandas as pd
d = {
'Image Index':
['00000013_005.jpeg', '00000013_026.jpeg',
'00000017_001.jpeg', '00000042_002.jpg',
'00000084_000.jpg', '00000099_003.jpg'],
'labels':
['Emphysima', 'Emphysima',
'No finding', 'No finding',
'Effusion', 'Effusion']}
df = pd.DataFrame(data=d)
df.head()
Image Index labels
0 00000013_005.jpeg Emphysima
1 00000013_026.jpeg Emphysima
2 00000017_001.jpeg No finding
3 00000042_002.jpg No finding
4 00000084_000.jpg Effusion
現在,根據你的需要,你可以試試這個
from pathlib import Path
from PIL import Image
# iterate over the unique label
for item_name in df.labels.unique():
# create folder according to the label name
item_folder = Path(f"{item_name}/")
item_folder.mkdir(parents=True, exist_ok=True)
# store id and gt for unique labels
id = []
gt = []
# iterate over all possible number of unique labels
for id_label in df.loc[df['labels'] == item_name].values.tolist():
# id_label :['image_id', 'label']
id.append(id_label[0]) # image_id
gt.append(id_label[1]) # label
img = Image.open(id_label[0]) # read the image
img.save(f'{item_folder}/{id_label[0]}') # and save to target folder
# save the individual ground truth
# to the concern directory
label = pd.DataFrame({
'Image Index': id,
'labels': gt
})
label.to_csv(f'{item_folder}/{item_folder}.csv', index=False)
它將按labels
名稱創建一個目錄,並將相應的圖像保存到該目錄,並僅使用它們的標簽創建一個新的data frame
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.