Optimize ImageStat.Stat._getextrema function

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 <andreas@florath.net>
This commit is contained in:
Andreas Florath 2023-12-01 15:26:09 +01:00
parent 76446ee450
commit 1b8f9d386b

View File

@ -53,17 +53,23 @@ class Stat:
"""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):