Skip to content

Commit

Permalink
Optimize ImageStat.Stat._getextrema function
Browse files Browse the repository at this point in the history
The optimzed function improves the performance.  The original function
always runs through the complete historgram of length 256 even if it
is possible to exit the loop early (break).

Running some tests I found performance improvements of factor >10
depending on the image.

Signed-off-by: Andreas Florath <[email protected]>
  • Loading branch information
florath committed Dec 1, 2023
1 parent 76446ee commit 1b8f9d3
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/PIL/ImageStat.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,23 @@ def _getextrema(self):
"""Get min/max values for each band in the image"""

def minmax(histogram):
n = 255
x = 0
res_min, res_max = 255, 0
for i in range(256):
if histogram[i]:
n = min(n, i)
x = max(x, i)
return n, x # returns (255, 0) if there's no data in the histogram
res_min = i
break
for i in range(255, -1, -1):
if histogram[i]:
res_max = i
break
if res_max >= res_min:
return res_min, res_max
else:
return (255, 0)

v = []
for i in range(0, len(self.h), 256):
v.append(minmax(self.h[i:]))
v.append(minmax(self.h[i:i+256]))
return v

def _getcount(self):
Expand Down

0 comments on commit 1b8f9d3

Please sign in to comment.