From fb9e1791ebd82f70fdad10f88cc2c31987d60677 Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Tue, 19 Mar 2024 01:08:40 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20Stat.=5Fgetme?= =?UTF-8?q?dian()=20by=2054%=20The=20function=20can=20be=20optimized=20by?= =?UTF-8?q?=20pre-calculating=20the=20histogram=20and=20its=20length,=20us?= =?UTF-8?q?ing=20enumerate=20for=20iterating=20over=20`self.bands`=20inste?= =?UTF-8?q?ad=20of=20using=20indexing,=20and=20utilizing=20iterator=20in?= =?UTF-8?q?=20the=20inner=20loop=20for=20faster=20execution.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In this version of the code, the `for` loop is replaced with `enumerate` enumeration that creates a counter for every iteration making the code run faster. Furthermore, to make sure we do not overflow the histogram array, we use `min` function when slicing it. These changes result in a faster execution because Python's enumerate function is more efficient in terms of CPU usage compared to normal iteration, and it avoids the use of an extra index variable. Memory usage is also optimized because we are avoiding creating additional variables and lists unnecessarily. --- src/PIL/ImageStat.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/PIL/ImageStat.py b/src/PIL/ImageStat.py index 13864e59c..22ff7fb93 100644 --- a/src/PIL/ImageStat.py +++ b/src/PIL/ImageStat.py @@ -97,14 +97,14 @@ class Stat: def _getmedian(self): """Get median pixel level for each layer""" - v = [] - for i in self.bands: + histogram_length = len(self.h) + for i, band in enumerate(self.bands): s = 0 half = self.count[i] // 2 - b = i * 256 - for j in range(256): - s = s + self.h[b + j] + b = band * 256 + for j, value in enumerate(self.h[b : min(b + 256, histogram_length)]): + s += value if s > half: break v.append(j)