Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If I understood correctly the <code>-level</code> option of ImageMagick, then the <code>level_image</code> function I provide should do what you want.</p> <p>Two things to note:</p> <ul> <li>the speed definitely can be improved</li> <li>it currently only works with RGB images</li> <li>the algorithm goes through the HSV colorspace, and affects only the V (brightness) component</li> </ul> <p>The code:</p> <pre><code>import colorsys class Level(object): def __init__(self, minv, maxv, gamma): self.minv= minv/255.0 self.maxv= maxv/255.0 self._interval= self.maxv - self.minv self._invgamma= 1.0/gamma def new_level(self, value): if value &lt;= self.minv: return 0.0 if value &gt;= self.maxv: return 1.0 return ((value - self.minv)/self._interval)**self._invgamma def convert_and_level(self, band_values): h, s, v= colorsys.rgb_to_hsv(*(i/255.0 for i in band_values)) new_v= self.new_level(v) return tuple(int(255*i) for i in colorsys.hsv_to_rgb(h, s, new_v)) def level_image(image, minv=0, maxv=255, gamma=1.0): """Level the brightness of image (a PIL.Image instance) All values ≤ minv will become 0 All values ≥ maxv will become 255 gamma controls the curve for all values between minv and maxv""" if image.mode != "RGB": raise ValueError("this works with RGB images only") new_image= image.copy() leveller= Level(minv, maxv, gamma) levelled_data= [ leveller.convert_and_level(data) for data in image.getdata()] new_image.putdata(levelled_data) return new_image </code></pre> <p>If there is some way to do the RGB→HSV conversion (and vice versa) using PIL, then one can split into the H, S, V bands, use the <code>.point</code> method of the V band and convert back to RGB, speeding up the process by a lot; however, I haven't found such a way.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload