Table of Contents

Python Scripts to Download Images of Hats and People

This is part of the project to identify objects with OpenCV / Tensorflow / Yolo / ImageAI.


Download Images of Hats

download_hats_images.py

import requests as req
import os as os
 
hardhatLoc = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n03492922'
 
hardhatImages = req.get(hardhatLoc).text
noOfImages = 0
 
if not os.path.exists('hardhat'):
    os.makedirs('hardhat')
 
os.chdir('hardhat')
for i in hardhatImages.split('\n'):
    try:
        r = req.get(i, timeout=0.5)
        file = i.split("/")[-1].split('\r')[0]
        if 'image/jpeg' in r.headers['Content-Type']:
            if len(r.content)> 8192:
                with open(file, 'wb') as outfile:
                    outfile.write(r.content)
                    noOfImages += 1
                    print('Success: ' + file)
            else:
                print('Failed: ' + file + ' -- Image too small')
        else:
            print('Failed: ' + file + ' -- Not an image')
 
    except Exception as e:
        print('Failed: ' + file + ' -- Error')

Download Images of People

download_people_images.py

import requests as req
import os as os
 
peopleLoc = 'http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n07942152'
 
peopleImages = req.get(peopleLoc).text
noOfImages = 0
 
if not os.path.exists('people'):
    os.makedirs('people')
 
os.chdir('people')
for i in peopleImages.split('\n'):
    try:
        r = req.get(i, timeout=0.5)
        file = i.split("/")[-1].split('\r')[0]
        if 'image/jpeg' in r.headers['Content-Type']:
            if len(r.content)> 8192:
                with open(file, 'wb') as outfile:
                    outfile.write(r.content)
                    noOfImages += 1
                    print('Success: ' + file)
            else:
                print('Failed: ' + file + ' -- Image too small')
        else:
            print('Failed: ' + file + ' -- Not an image')
 
    except Exception as e:
        print('Failed: ' + file + ' -- Error')
 
print('*********** Download Finished **************')