-
Notifications
You must be signed in to change notification settings - Fork 0
/
image.py
88 lines (75 loc) · 2.1 KB
/
image.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
import os
import sys
import csv
from urllib import error
from urllib import request
from PIL import Image
from io import BytesIO
def download_image(key, url):
filename = '{}.jpg'.format(key)
if os.path.exists(filename):
print('Image {} already exists. Skipping download.'.format(filename))
return 0
try:
response = request.urlopen(url)
image_data = response.read()
except:
print('Warning: Could not download image {} from {}'.format(key, url))
writer.writerow(
{
'error': "download",
"filename": filename,
'key': key,
"url": url
}
)
return 1
try:
pil_image = Image.open(BytesIO(image_data))
except:
print('Warning: Failed to parse image {}'.format(key))
writer.writerow(
{
'error': "parse",
"filename": filename,
'key': key,
"url": url
}
)
return 1
try:
pil_image_rgb = pil_image.convert('RGB')
except:
print('Warning: Failed to convert image {} to RGB'.format(key))
writer.writerow(
{
'error': "convert",
"filename": filename,
'key': key,
"url": url
}
)
return 1
try:
pil_image_rgb.save(filename, format='JPEG', quality=90)
except:
print('Warning: Failed to save image {}'.format(filename))
writer.writerow(
{
'error': "save",
"filename": filename,
'key': key,
"url": url
}
)
return 1
return 0
csvfile = open("image.csv", 'r')
csvreader = csv.reader(csvfile)
key_url_list = [line[:2] for line in csvreader]
key_url_list = key_url_list[1:]
with open('logs.csv', 'w', newline='') as f:
writer = csv.DictWriter(f, fieldnames=['error', 'key', 'url', 'filename'])
writer.writeheader()
for key, url in key_url_list:
download_image(key, url)