[Image-SIG] How to apply a threshold value to the image

Fredrik Lundh fredrik at pythonware.com
Sat Nov 10 11:44:55 CET 2007

export at hope.cz wrote:

> But how should the 256-item mapping table  look like, if the
 > threshold is 18( found from the histogram)

here's one way to do it:

threshold = 18

table = []
for i in range(256):
     if i < threshold:
         table.append(0) # black
         table.append(255) # white

out = im.point(table)

there are shorter ways to write this; the above was written for clarity. 
  quite often, passing in a function instead of a table can make the 
code shorter:

threshold = 18

def map(i):
     if i < threshold:
         return 0
     return 255

out = im.point(table)

there are plenty of ways to do this in one line as well, but I'll leave 
that as an exercise.


More information about the Image-SIG mailing list