1. 程式人生 > >如何快速構建深度學習影象資料集

如何快速構建深度學習影象資料集

1、介紹

為了構建我們的深度學習影象資料集,我們將利用微軟的Bing影象搜尋API,這是微軟認知服務的一部分,用於將AI應用在視覺,語音,文字等的軟體。

2、建立您的Cognitive Services帳戶

點選下面的網頁進入: https://azure.microsoft.com/en-us/try/cognitive-services/?api=bing-image-search-api 如截圖中,要註冊Bing影象搜尋API,請單擊“獲取API金鑰”按鈕。 從那裡您可以通過登入您的Microsoft,Facebook,LinkedIn或GitHub帳戶進行註冊(為了簡單起見,我使用GitHub)。 完成註冊過程後,您將在您的API頁面看到類似於我的瀏覽器的頁面:

3、使用Python構建深度學習資料集

3.1 閱讀文件

如果您對 API如何工作我們在發出搜尋請求後如何使用API​​ 有任何疑問,您應該參考這兩個頁面。

3.2 安裝requests包

$ workon your_env_name
$ pip install requests
  • 1
  • 2

3.3 建立指令碼檔案SearchBingAPI.py來下載影象

'''
任務: 利用BING API從網上抓取特定圖片,作為人臉識別的資料集。
操作: 1. 在linux下,命令列輸入: python SearchBingAPI.py --query "鍾漢良" --output DataSet/ZhongHanLiang
      2. 註釋掉ap.add_argument部分,對建立的args字典直接輸入值後,執行SearchBingAPI檔案即可。
    - 2018/7/4
    - kerrwy
'''
from requests import exceptions import argparse import requests import cv2 import os # 1. 解析輸入引數 ap = argparse.ArgumentParser() # ap.add_argument("-q", "--query", required=True, # help="search query to Bing Image APT for") # ap.add_argument("-o", "--output", required=True, # help="path to output directory of image")
args = vars(ap.parse_args()) # vars() 函式返回物件object的屬性和屬性值的字典物件,接收的物件為命令列中輸入的。 # args["query"] = "鍾漢良" # try: # os.mkdir("./DataSet/ZhongHanLiang") # except Exception as e: # print("[INFO] Path have made.") # # args["output"] = r"./DataSet/ZhongHanLiang" # args["query"] = "鄧超" # try: # os.mkdir("./DataSet/DengChao") # except Exception as e: # print("[INFO] Path have made.") # # args["output"] = r"./DataSet/DengChao" # args["query"] = "蔣勤勤" # try: # os.mkdir("./DataSet/JiangQinQin") # except Exception as e: # print("[INFO] Path have made.") # # args["output"] = r"./DataSet/JiangQinQin" args["query"] = "趙麗穎" try: os.mkdir("./DataSet/ZhaoLiYing") except Exception as e: print("[INFO] Path have made.") args["output"] = r"./DataSet/ZhaoLiYing" # 2. 配置一些全域性變數 MAX_RESULTS = 50 # 總共需要的圖片張數 GROUP_SIZE = 25 # 每頁搜尋多少張 API_KEY = "abd938ec58594f5f9aa680d030175fcc" URL = "https://api.cognitive.microsoft.com/bing/v7.0/images/search" # 3. 先列出搜尋過程中可能出現的異常,在後面捕捉並優雅處理。 EXCEPTIONS = set([IOError, FileNotFoundError, exceptions.RequestException, exceptions.HTTPError, exceptions.ConnectionError, exceptions.Timeout]) # 4. 初始化搜尋引數並進行搜尋 term = args["query"] # 影象查詢內容:如胡歌 headers = {"Ocp-Apim-Subscription-key": API_KEY} params = {"q": term, "offset": 0, "count": GROUP_SIZE} print("[INFO] searching Bing API for '{}'".format(term)) search = requests.get(URL, headers=headers, params=params) search.raise_for_status() result = search.json() estNumResults = min(result["totalEstimatedMatches"], MAX_RESULTS) print("[INFO] {} total result for '{}'".format(estNumResults, term)) total = 0 # 5.批處理結果的估計數量,搜尋5次,每次50張 for offset in range(0, estNumResults, GROUP_SIZE): print("[INFO] Making request for group {}-{} of {}...".format(offset, offset+GROUP_SIZE, estNumResults)) params["offset"] = offset search = requests.get(URL, headers=headers, params=params) search.raise_for_status() result = search.json() print("[INFO] saving images for group {}-{} of {}...".format(offset, offset+GROUP_SIZE, estNumResults)) # 6. 儲存當前批次中的影象 for v in result["value"]: try: # 請求下載影象 print("[INFO] fetching: {}".format(v["contentUrl"])) r = requests.get(v["contentUrl"], timeout=30) # 定義輸出影象的路徑 ext = v["contentUrl"][v["contentUrl"].rfind("."):] # '.jpg' p = os.path.sep.join([args["output"], "{}{}".format(str(total).zfill(8), ext)]) # 路徑分割符'/' # 影象寫入磁碟 f = open(p, "wb") f.write(r.content) f.close() # 捕捉不能下載影象的錯誤 except Exception as e: if type(e) in EXCEPTIONS: print("[INFO] Skipping: {}".format(v["contentUrl"])) continue image = cv2.imread(p) if image is None: print("[INFO] deleting: {}".format(p)) # 從磁碟中刪除 os.remove(p) continue

我們可以通過使用一些find 計算每個查詢下載的影象總數。

$ find . -type d -print0 | while read -d '' -r dir; do
> files=("$dir"/*)
> printf "%5d files in directory %s\n" "${#files[@]}" "$dir"
> done
    2 files in directory .
    5 files in directory ./dataset
  235 files in directory ./dataset/bulbasaur
  245 files in directory ./dataset/charmander
  245 files in directory ./dataset/mewtwo
  238 files in directory ./dataset/pikachu
  230 files in directory ./dataset/squirtle

4、結束語

正如你所看到的,你只需要刪除每個類的一些影象。Bing Image Search API工作得非常好!