机器学习或深度学习的第一步是获取数据集,一般我们使用业务数据集或公共数据集。本文将介绍使用 Bing Image Search API 和 Python 脚本,快速的建立自己的图片数据集。

1. 快速建立图片数据集,我们将使用 Bing Image Search API 建立自己的图片数据集。

首先进入 Bing Image Search API 网站:点击链接

点击“Get API Key”按钮

选择7天试用,点击“Get start”按钮

同意微软服务条款和勾选地区,点击“Next”按钮

可以使用你的 Microsoft, Facebook, LinkedIn, 或 GitHub 账号登陆,我使用我的 GitHub 账号登陆。

注册完成,进入Your APIs 页面。如下图所示:

向下拖动,可以查看可以使用的API列表和API Keys,注意红框部分,将在后面部分使用到。

至此,你已经有一个Bing Image Search API账号,并可以使用 Bing Image Search API 了。你可以访问:

  • Quickstart: Search for images using the Bing Image Search REST API and Python
  • How to page through results from the Bing Web Search API

了解更多关于 Bing Image Search API 如何使用的信息。下面将介绍编写Python脚本,使用 Bing Image Search API 下载图片。

2. 编写Python脚本下载图片

首先安装 requests 包,在终端执行命令

$ pip install requests

新建一个文件,命名为 search_bing_api.py,插入以下代码

# import the necessary packages
from requests import exceptions
import argparse
import requests
import os
import cv2# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-q", "--query", required=True,help="search query to search Bing Image API for")
args = vars(ap.parse_args())query = args["query"]
output = "/Users/simon/AI/dataset/" + query# set your Microsoft Cognitive Services API key along with (1) the
# maximum number of results for a given search and (2) the group size
# for results (maximum of 50 per request)
API_KEY = "YOUR Bing Image Search API Key"
MAX_RESULTS = 250
GROUP_SIZE = 50# set the endpoint API URL
URL = "https://api.cognitive.microsoft.com/bing/v7.0/images/search"# when attempting to download images from the web both the Python
# programming language and the requests library have a number of
# exceptions that can be thrown so let's build a list of them now
# so we can filter on them
EXCEPTIONS = set([IOError, FileNotFoundError,exceptions.RequestException, exceptions.HTTPError,exceptions.ConnectionError, exceptions.Timeout])# store the search term in a convenience variable then set the
# headers and search parameters
term = query
headers = {"Ocp-Apim-Subscription-Key" : API_KEY}
params = {"q": term, "offset": 0, "count": GROUP_SIZE}# make the search
print("[INFO] searching Bing API for '{}'".format(term))
search = requests.get(URL, headers=headers, params=params)
search.raise_for_status()# grab the results from the search, including the total number of
# estimated results returned by the Bing API
results = search.json()
estNumResults = min(results["totalEstimatedMatches"], MAX_RESULTS)
print("[INFO] {} total results for '{}'".format(estNumResults,term))# initialize the total number of images downloaded thus far
total = 0# loop over the estimated number of results in `GROUP_SIZE` groups
for offset in range(0, estNumResults, GROUP_SIZE):# update the search parameters using the current offset, then# make the request to fetch the resultsprint("[INFO] making request for group {}-{} of {}...".format(offset, offset + GROUP_SIZE, estNumResults))params["offset"] = offsetsearch = requests.get(URL, headers=headers, params=params)search.raise_for_status()results = search.json()print("[INFO] saving images for group {}-{} of {}...".format(offset, offset + GROUP_SIZE, estNumResults))# loop over the resultsfor v in results["value"]:# try to download the imagetry:# make a request to download the imageprint("[INFO] fetching: {}".format(v["contentUrl"]))r = requests.get(v["contentUrl"], timeout=30)# build the path to the output imageext = v["contentUrl"][v["contentUrl"].rfind("."):]p = os.path.sep.join([output, "{}{}".format(str(total).zfill(8), ext)])# write the image to diskf = open(p, "wb")f.write(r.content)f.close()image = cv2.imread(p)# if the image is `None` then we could not properly load the# image from disk (so it should be ignored)if image is None:print("[INFO] deleting: {}".format(p))os.remove(p)continue# catch any errors that would not unable us to download the# imageexcept Exception as e:# check to see if our exception is in our list of# exceptions to check forif type(e) in EXCEPTIONS:print("[INFO] skipping: {}".format(v["contentUrl"]))continue# update the countertotal += 1

以上为所有的Python下载图片代码,注意以下红框部分替换为自己的文件目录和自己的 Bing Image Search API Key。

3. 运行下载脚本,下载图片

创建图片存储主目录,在终端执行命令

$ mkdir dataset

创建当前下载内容的存储目录,在终端执行命令

$ mkdir dataset/pikachu

终端执行命令如下命令,开始下载图片

$ python search_bing_api.py --query "pikachu"
[INFO] searching Bing API for 'pikachu'
[INFO] 250 total results for 'pikachu'
[INFO] making request for group 0-50 of 250...
[INFO] saving images for group 0-50 of 250...
[INFO] fetching: http://images5.fanpop.com/image/photos/29200000/PIKACHU-pikachu-29274386-861-927.jpg
[INFO] skipping: http://images5.fanpop.com/image/photos/29200000/PIKACHU-pikachu-29274386-861-927.jpg
[INFO] fetching: http://images6.fanpop.com/image/photos/33000000/pikachu-pikachu-33005706-895-1000.png
[INFO] skipping: http://images6.fanpop.com/image/photos/33000000/pikachu-pikachu-33005706-895-1000.png
[INFO] fetching: http://images5.fanpop.com/image/photos/31600000/Pikachu-with-pokeball-pikachu-31615402-2560-2245.jpg

按照相同的方法下载其他图片:charmander,squirtle,bulbasaur,mewtwo

下载 charmander

$ mkdir dataset/charmander
$ python search_bing_api.py --query "charmander"

下载 squirtle

$ mkdir dataset/squirtle
$ python search_bing_api.py --query "squirtle"

下载 bulbasaur

$ mkdir dataset/bulbasaur
$ python search_bing_api.py --query "bulbasaur"

下载 mewtwo

$ mkdir dataset/mewtwo
$ python search_bing_api.py --query "mewtwo"

下载的图片如下图所示

下载全部完成大约需要30多分钟时间,最终五个文件夹下的图片内容如下

为了更好的训练模型,我们应该进行图片筛选,将不合适的图片删除掉。比如在某一个分类文件夹下,将不属于这个分类的图片删除掉,将包含了其他分类的图片删除等。筛选方法为,打开文件夹,浏览图片,手工进行筛选。

至此我们已经建立自己的图片数据集了。下一节 深度学习入门(二)训练并使用Keras模型 模型中,我们将使用到这个图片数据集。

扫码关注公众号,回复"数据集",可以获取这个图片数据集

深度学习入门(一)快速建立自己的图片数据集相关推荐

  1. 深度学习入门与快速实践

    深度学习介绍 以深度学习为主要力量的AI浪潮徐徐展开 我们正处在一个巨变的时代,人工智能已经成为了这个时代的主题.人工智能成为第四次工业革命的核心驱动力,并将像机械化.电气化.信息化一样,最终会渗透到 ...

  2. 深度学习入门——利用卷积神经网络训练CIFAR—10数据集

    CIFAR-10数据集简介 CIFAR-10是由Hinton的学生Alex Krizhevsky和Ilya Sutskever整理的一个用于普适物体的小型数据集.它一共包含10个类别的RGB彩色图片: ...

  3. 给深度学习入门者的Python快速教程 - 番外篇之Python-OpenCV

    转载自:https://zhuanlan.zhihu.com/p/24425116 本篇是前面两篇教程:给深度学习入门者的Python快速教程 - 基础篇 给深度学习入门者的Python快速教程 - ...

  4. 【完结】给新手的12大深度学习开源框架快速入门项目

    文/编辑 | 言有三 这是一篇总结文,给大家来捋清楚12大深度学习开源框架的快速入门,这是有三AI的GitHub项目,欢迎大家star/fork. https://github.com/longpen ...

  5. 给深度学习入门者的Python快速教程 - numpy和Matplotlib篇

    转载自:https://zhuanlan.zhihu.com/p/24309547 本篇部分代码的下载地址: https://github.com/frombeijingwithlove/dlcv_f ...

  6. 深度学习入门指北——从硬件到软件

    作者:隔壁王大喵 近日,Rachel Thomas在fast.ai上发布了一篇博文<What you need to do deep learning>,他希望通过这篇文章回答一些深度学习 ...

  7. LeCun亲授的深度学习入门课:从飞行器的发明到卷积神经网络

    Root 编译整理 量子位 出品 | 公众号 QbitAI 深度学习和人脑有什么关系?计算机是如何识别各种物体的?我们怎样构建人工大脑? 这是深度学习入门者绕不过的几个问题.很幸运,这里有位大牛很乐意 ...

  8. 使用TensorFlow.js在浏览器中进行深度学习入门

    目录 设置TensorFlow.js 创建训练数据 检查点 定义神经网络模型 训练AI 测试结果 终点线 内存使用注意事项 下一步是什么?狗和披萨? 下载TensorFlowJS示例-6.1 MB T ...

  9. LSTM长短记,长序依赖可追忆(深度学习入门系列之十四)

    摘要:如果你是一名单身狗,不要伤心,或许是因为你的记忆太好了.有时,遗忘是件好事,它让你对琐碎之事不再斤斤计较.然而每当自己记不住单词而"问候亲人"时,也确实气死个人.于是你懂得了 ...

最新文章

  1. js调用php函数兵每秒刷新,深入理解JavaScript立即调用函数表达式(IIFE)
  2. linux建立普通用户命令,Linux普通用户执行特定的命令配置
  3. Ubuntu 安装 Apache Airflow
  4. Clean Code 《代码整洁之道》前四章读书笔记
  5. 广播中等待较久出现anr问题
  6. BERT-从业者的观点
  7. CentOS 7下载地址(ISO文件)
  8. GMSK调制解调器 matlab viterbi解调采用维特比解调性能具有很大优势
  9. 类库、框架、模块、组件等概念介绍
  10. C语言上机复习(一)文件操作
  11. 转载:JAVE 视音频转码
  12. java rotateright_Java Tetris旋转
  13. cont在c语言用法,在S7-1500中指令TSEND_C and TRCV_C如何使用?
  14. 跟着迪哥学python 经管之家_跟着迪哥学:Python数据分析与机器学习实战
  15. Linux内存管理(一):综述
  16. FCN全卷积网络模型——高分辨率遥感影像地物识别
  17. MySQL While循环语句
  18. python翻页爬豆瓣影评_Python超级简单的爬虫案例--爬豆瓣影评为例
  19. 如何用canvas实现五子棋
  20. zookeeper客户端使用与集群特性

热门文章

  1. BI神器Power Query(21)-- 同一列内多重替换(1)
  2. openpyxl修改图表标题字体和字号
  3. python培训千锋和黑马哪个好
  4. linux精确匹配文件名,Linux基础知识之文件名匹配
  5. 同相放大器、反相放大器的区别与优劣
  6. 学生选课系统C语言系统的说明文档,C语言学生选课系统(代码)
  7. 【LTE】Qualcomm LTE Packets log 分析(三)LTE Access Stratum Log Analysis
  8. 红米note3全网通版刷机救砖 9008强刷(无需短接)
  9. 二分法中为啥常用mid=beg+(end-beg)/2 而非mid=(beg+end)/2 ?
  10. 浩辰3D软件新手入门攻略:草图绘制功能全解析!