-
Notifications
You must be signed in to change notification settings - Fork 1
/
average.py
234 lines (168 loc) · 6.17 KB
/
average.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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/python
"""Usage: python average.py [OPTIONS] TAGS
TAGS is a space delimited list of tags
OPTIONS:
-w screenwidth or --width screenwidth
-h screenheight or --height screenheight
-f filename or --file filename
-n photos or --number photos
-u or --unique unique users
-p or --page start collection at search page idx
0 = first page
Requires:
- Python Imaging Library [http://www.pythonware.com/products/pil/]
- Python >= 2.2
"""
# THIS SOFTWARE IS SUPPLIED WITHOUT WARRANTY OF ANY KIND, AND MAY BE
# COPIED, MODIFIED OR DISTRIBUTED IN ANY WAY, AS LONG AS THIS NOTICE
# AND ACKNOWLEDGEMENT OF AUTHORSHIP REMAIN.
__author__ = "Neil Kandalgaonkar <neilk(a)brevity.org>"
# Purpose:
# generate an "average" image from Flickr based on tags.
#
# This may have to be completely rewritten. It's very buggy and has fits and starts,
# not to mention Flickr's occasional slowness. There is a problem with the image
# slowly converging on blackness.
#
# We should really cache the images on disk (and the search results)
# and then have at them.
import sys
import urllib
import math
import Image
import flickr
import time
from flickr import FlickrError
# we want to get N photos that match the tag.
def get_photos_for_tags(tags, number=50, unique_owners=False, start_page=0):
photos = []
seen_owner = {}
page = start_page
need_more = True
debug("starting to get photos...")
while (need_more):
page += 1
debug("page %s of photo search" % page)
for p in flickr.photos_search(tags=tags, tag_mode='all', page=page):
debug ("photo id %s" % p.id)
if unique_owners:
# silly thing is unicode, although just a number.
uid = p.owner.id.encode('ascii')
debug (" photo has uid %s" % uid)
if seen_owner.has_key(uid): continue
seen_owner[uid] = 1
photos.append(p)
if (len(photos) == number):
need_more = False
break
return photos
def resize(im, screen, standard_area):
(screen_width, screen_height) = screen
(width, height) = im.size
# resize here to all occupy about the same area on screen.
area = width * height
factor = math.sqrt( standard_area * 1.0 / area )
width *= factor
height *= factor
# but stay within the maximum screen.
if width > screen_width or height > screen_height:
# landscape
if width > height:
width = screen_width
height *= screen_width / width
# portrait
else:
width *= screen_height / height
height = screen_height
width = int(width)
height = int(height)
return im.resize((width,height), Image.BICUBIC)
def create_average(screen, photos):
debug("starting")
# some geometry
(screen_width, screen_height) = screen
center_x = screen_width / 2;
center_y = screen_height / 2;
# we will resize all photos to have an area around this.
phi = (1 + math.sqrt(5)) / 2
standard_area = screen_width * (screen_width/phi)
# prototype black screen all images get pasted onto.
black = Image.new("RGB", screen, "black")
average = black.copy()
for i in range(len(photos)):
debug("doing photo id %s" % photos[i].id)
try:
im = load_image(photos[i]);
except FlickrError:
debug("FlickrError")
continue
im.save("orig/%03d.jpg" % i)
im = resize(im, screen, standard_area);
# paste photo in the center of a black screen.
(im_width, im_height) = im.size
offset_x = center_x - im_width / 2;
offset_y = center_y - im_height / 2;
im_frame = black.copy()
im_frame.paste(im, (offset_x,offset_y))
# and blend this with our average
alpha = 1.0/(i+1) # <-- clever part. Get average in constant memory.
# perhaps too clever.
# images where most of the detail is just squished into one or two
# bits of depth. This may account for the slow darkening (?)
# may be better to combine images in a tree
average = Image.blend(average, im_frame, alpha);
if not (i % 10):
average.save('progress-%03d.jpg' % i)
# is this necessary? jclark had it.
del im
time.sleep(2) # be nice to their server
return average
def load_image(photo):
url = photo.getURL(size='Medium', urlType='source')
file, mime = urllib.urlretrieve(url)
im = Image.open(file)
return im
def debug(msg):
sys.stderr.write(msg + "\n")
def main(*argv):
from getopt import getopt, GetoptError
try:
(opts, args) = getopt(argv[1:], 'p:w:h:f:n:u', ['page', 'width', 'height', 'file', 'number','unique'])
except GetoptError, e:
print e
print __doc__
return 1
file = 'average.jpg'
width = 500
height = 500
n = 100
unique_owners = False
start_page = 0
for o, a in opts:
if o in ('-w', '--width'):
width = int(a)
elif o in ('-h', '--height'):
height = int(a)
elif o in ('-f', '--file'):
file = a
elif o in ('-n', '--number'):
n = int(a)
elif o in ('-u', '--unique'):
unique_owners = True
elif o in ('-p', '--page'):
start_page = int(a)
else:
print "Unknown argument: %s" % o
print __doc__
return 1
if len(args) == 0:
print "You must specify at least one tag"
print __doc__
return 1
tags = [item for item in args]
screen = (width, height)
photos = get_photos_for_tags(tags, n, unique_owners, start_page)
average = create_average(screen, photos)
average.save(file)
if __name__ == '__main__':
sys.exit(main(*sys.argv))