Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize ImageStat.Stat.extrema #7593

Merged
merged 5 commits into from Dec 6, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 12 additions & 6 deletions src/PIL/ImageStat.py
Expand Up @@ -53,17 +53,23 @@
"""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)

Check warning on line 68 in src/PIL/ImageStat.py

View check run for this annotation

Codecov / codecov/patch

src/PIL/ImageStat.py#L68

Added line #L68 was not covered by tests
florath marked this conversation as resolved.
Show resolved Hide resolved

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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can also use list comprehension

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My idea was to have a minimal patch set.

If you want, we could go with

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

My tests showed that from the performance point of view the two solutions are mostly the same. But if my other patch gets accepted #7599 the list comprehension might be the way to go to have the same style.

What do you think?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#7597 has actually just been merged to use list comprehension here. Would you like to resolve the conflict?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


def _getcount(self):
Expand Down