2
# The Python Imaging Library.
5
# global image statistics
8
# 1996-04-05 fl Created
9
# 1997-05-21 fl Added mask; added rms, var, stddev attributes
10
# 1997-08-05 fl Added median
11
# 1998-07-05 hk Fixed integer overflow error
14
# This class shows how to implement delayed evaluation of attributes.
15
# To get a certain value, simply access the corresponding attribute.
16
# The __getattr__ dispatcher takes care of the rest.
18
# Copyright (c) Secret Labs AB 1997.
19
# Copyright (c) Fredrik Lundh 1996-97.
21
# See the README file for information on usage and redistribution.
28
# The <b>ImageStat</b> module calculates global statistics for an
29
# image, or a region of an image.
33
# Calculate statistics for the given image. If a mask is included,
34
# only the regions covered by that mask are included in the
38
"Get image or feature statistics"
41
# Create a statistics object.
43
# @def __init__(image, mask=None)
44
# @param image A PIL image, or a precalculate histogram.
45
# @param mask An optional mask.
47
def __init__(self, image_or_list, mask = None):
50
self.h = image_or_list.histogram(mask)
52
self.h = image_or_list.histogram()
53
except AttributeError:
54
self.h = image_or_list # assume it to be a histogram list
55
if type(self.h) != type([]):
56
raise TypeError, "first argument must be image or list"
57
self.bands = range(len(self.h) / 256)
59
def __getattr__(self, id):
60
"Calculate missing attribute"
62
raise AttributeError, id
63
# calculate missing attribute
64
v = getattr(self, "_get" + id)()
68
def _getextrema(self):
69
"Get min/max values for each band in the image"
71
def minmax(histogram):
78
return n, x # returns (255, 0) if there's no data in the histogram
81
for i in range(0, len(self.h), 256):
82
v.append(minmax(self.h[i:]))
86
"Get total number of pixels in each layer"
89
for i in range(0, len(self.h), 256):
90
v.append(reduce(operator.add, self.h[i:i+256]))
94
"Get sum of all pixels in each layer"
97
for i in range(0, len(self.h), 256):
100
sum = sum + j * self.h[i+j]
105
"Get squared sum of all pixels in each layer"
108
for i in range(0, len(self.h), 256):
111
sum2 = sum2 + (j ** 2) * float(self.h[i+j])
116
"Get average pixel level for each layer"
120
v.append(self.sum[i] / self.count[i])
123
def _getmedian(self):
124
"Get median pixel level for each layer"
139
"Get RMS for each layer"
143
v.append(math.sqrt(self.sum2[i] / self.count[i]))
148
"Get variance for each layer"
153
v.append((self.sum2[i]-(self.sum[i]**2.0)/n)/n)
156
def _getstddev(self):
157
"Get standard deviation for each layer"
161
v.append(math.sqrt(self.var[i]))
164
Global = Stat # compatibility