-
Notifications
You must be signed in to change notification settings - Fork 5
/
avgimg.py
executable file
·62 lines (43 loc) · 1.48 KB
/
avgimg.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
#!/usr/bin/env python
'''
Average images with PIL.
avgimg.py input... output
We rely on numpy for capacious but fast types to hold the running sum,
and on PIL for reading and writing, including guessing the format you
want from the file suffix.
Todo:
+ More docs
+ Use an int type for the running sum
+ Refuse to clobber an existing output file?
+ Better error-checking in general
'''
from sys import argv, exit
import Image
import time
from numpy import *
avgtype = float32
avg = array([])
# should probably be called running_sum, though, right?
n = float(len(argv)-2) # -1 for our filename, -1 for the ouput file
print 'Averaging %s images in %s' % (int(n), argv[1:-1])
start = time.time()
for imgfile in argv[1:-1]:
try:
img = Image.open(imgfile)
except:
print('Could not read "%s"!' % (imgfile))
continue
if avg.shape == (0,):
avg = asarray(img).copy()
avg = avg.astype(avgtype)
avg.fill(0.0) # fixme: use a zeros() function for speed
else:
if img.size != (avg.shape[1], avg.shape[0]):
exit('"%s" is not the same shape as the earlier images!' % (imgfile))
# Wait, why do we continue on failure to open, but die if the images
# aren't the same dimensions? Consistent this up a notch.
avg = avg + asarray(img).astype(avgtype)/n
print 'Main loop: %s pixels per second.' % ((n * avg.shape[1] * avg.shape[0]) / (time.time() - start))
avg = avg.astype(uint8) # should add support for, like, float32 TIFFs
avgimg = Image.fromarray(avg)
avgimg.save(argv[-1])