Setting an Image File Values

Mike C. Fletcher mcfletch at rogers.com
Tue May 4 02:47:52 EDT 2004


W. Watson wrote:

> I have a 640x480 b/w bmp image file that can be converted to a dat 
> file. I would like to convert the value of each pixel that is below 
> say 120 units to exactly 40 units.

...

>   python -c "open('mask.dat','w').write(chr(40)*640*480)"

Well, if you're going to take this as the baseline, then we can do some 
pretty darn simple stuff indeed:

 >>> import string
 >>> def createMask( threshold=120, target=40 ):
...     """Create 256-char mapping of destination characters"""
...     return string.maketrans( "".join( [chr(x) for x in 
range(threshold)]), chr(target) * threshold )
...
 >>> data = open( "p:\\drawcurve.py", 'rb' ).read() # mode 'rb' is 
important! use 'wb' to write
 >>> mask = createMask()
 >>> data
"'''Test of the glVertex function\r\n\r\nDrawing TT glyphs as Cubic 
splines...\r\n\thttp://support.microsoft.com/support/kb/articles/q243/2/85.asp\r\n\r\n'''\r\nfrom 
OpenGLContext import testingcontext\r\nBaseContext"
 >>> data.translate( mask )
'((((((((((((((((((((((x((((((((((((((((((((((((((y(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((x(((((((((((((((((((((x((((((((((((x('
 >>> ord('x') # just to see why x and y show up...
120

Of course, most Python programmers, when faced with a problem like this 
would turn to either PIL (Python Imaging Library) or Numpy (Numeric 
Python), but if all you need is quick-and-dirty, there you go.

Have fun,
Mike

_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list