forked from MusaTamzid05/ImageNetDownloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_downloader.py
174 lines (116 loc) · 4.45 KB
/
image_downloader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import requests
from requests.exceptions import HTTPError
from requests.exceptions import ConnectionError
from requests.exceptions import TooManyRedirects
from requests.exceptions import InvalidSchema
from requests.exceptions import ReadTimeout
from requests.exceptions import MissingSchema
import shutil
import os
import argparse
from PIL import UnidentifiedImageError
from PIL import Image
class ImageDownloader:
def __init__(self , url):
self.links = self.get_links(url)
if len(self.links) == 0:
exit(1)
print("Total links : {}".format(len(self.links)))
def get_starting_index(self , path):
files = os.listdir(path)
if len(files) == 0:
return 0
indexes = [int(file_.split(".")[0]) for file_ in files]
return max(indexes) + 1
def start(self , save_dir , image_count):
if os.path.isdir(save_dir) == False:
os.mkdir(save_dir)
print("Directory {} created.".format(save_dir))
current_image_index = 0
else:
current_image_index = self.get_starting_index(save_dir)
if image_count > len(self.links):
print("there are less image found than required")
image_count = len(self.links)
print("Setting max image count to : {}".format(image_count))
try:
visited_link_index = current_image_index
for _ in self.links:
link = self.links[visited_link_index]
ext = self.get_ext(link)
path = os.path.join(save_dir , str(current_image_index) + "." + ext )
if self.download(link , path , ext):
print("{}.downloaded => {}".format(current_image_index , link))
current_image_index += 1
if current_image_index >= image_count:
break
else:
print("Could not download : {}".format(link))
visited_link_index += 1
except KeyboardInterrupt:
print("Exiting")
finally:
if image_count != current_image_index:
print("Could download required number of image,total image downloaded : {}".format(current_image_index))
def download(self , url , save_path , ext):
res = None
try:
res = requests.get(url , timeout = 120, stream = True)
except HTTPError :
return False
except ConnectionError:
return False
except TooManyRedirects:
return False
except InvalidSchema:
return False
except ReadTimeout:
print("timed out.")
return False
except MissingSchema:
return False
return self.save_response(res , save_path , ext)
def save_response(self , res , save_path , ext):
with open(save_path, "wb") as f:
res.raw.decode_content = True
shutil.copyfileobj(res.raw , f)
if self.is_valid(save_path):
return True
os.remove(save_path)
return False
def is_valid(self , path):
try:
Image.open(path)
except UnidentifiedImageError:
print("Invalid image")
return False
return True
def get_ext(self , url):
parts = url.split('.')
ext = parts[-1]
if ext in ["jpg" , "jpeg" , "gif" , "tiff" , "png"]:
return ext
return "jpg"
def get_links(self , url):
res = None
try:
res = requests.get(url)
except HTTPError:
print("Error downloading links")
return []
text = res.text
urls = text.split("\n")
return urls
def tested():
image_downloader = ImageDownloader(url = "http://www.image-net.org/api/text/imagenet.synset.geturls?wnid=n03791235")
image_downloader.start("./cars" , 150)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--url', dest = "url" , required = True , type = str , help='imagenet url')
parser.add_argument('--save_dir', dest = "save_dir" , required = True , type = str , help='save dir')
parser.add_argument('--count', dest = "count" , type = int , required = True , help='image count')
args = parser.parse_args()
image_downloader = ImageDownloader(args.url)
image_downloader.start(args.save_dir , args.count)
if __name__ == "__main__":
main()