1. 程式人生 > >資料集生成方法:Python讀取txt檔案中的URL路徑並下載圖片

資料集生成方法:Python讀取txt檔案中的URL路徑並下載圖片

1.資料來源:

可針對自己的模型需要在imagenet官網上下載所需類別對應的txt檔案。

2.資料下載:

import os
from urllib.request import urlretrieve

def download():
    categories = ['bird', 'fish','invertebrate','mammal']  #需要下載圖片所對應的txt檔案
    for category in categories:
        #將下載到的圖片儲存在資料夾dataset中
        os.makedirs('./dataset1/%s' % category, exist_ok=True)
        #txt檔案所在路徑
        with open('./Animal/%s.txt' % category, 'r') as file:
            urls = file.readlines()
            n_urls = len(urls)
            for i, url in enumerate(urls):
                try:
                    urlretrieve(url.strip(), './Animal/%s/%s' % (category, url.strip().split('/')[-1]))
                    print('%s %i/%i' % (category, i, n_urls))
                except:
                    print('%s %i/%i' % (category, i, n_urls), 'no image')

if __name__ == '__main__':
    download()