title: numpy uint8 pixel wrapping solution
body: <p>For an image processing class, I am doing point operations on monochrome images. Pixels are uint8 [0,255]. </p>
  
  <p>numpy uint8 will wrap. For example, 235+30 = 9. I need the pixels to saturate (max=255) or truncate (min=0) instead of wrapping.</p>
  
  <p>My solution uses int32 pixels for the point math then converts to uint8 to save the image.</p>
  
  <p>Is this the best way? Or is there a faster way?</p>
  
  <pre><code>#!/usr/bin/python
  
  import sys
  import numpy as np
  import Image
  
  def to_uint8( data ) :
      # maximum pixel
      latch = np.zeros_like( data )
      latch[:] = 255
      # minimum pixel
      zeros = np.zeros_like( data )
  
      # unrolled to illustrate steps
      d = np.maximum( zeros, data )
      d = np.minimum( latch, d )
  
      # cast to uint8
      return np.asarray( d, dtype="uint8" )
  
  infilename=sys.argv[1]
  img = Image.open(infilename)
  data32 = np.asarray( img, dtype="int32")
  data32 += 30
  data_u8 = to_uint8( data32 )
  outimg = Image.fromarray( data_u8, "L" )
  outimg.save( "out.png" )
  </code></pre>
  
  <p>Input image:<br />
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/8/82/Georg_Friedrich_Bernhard_Riemann.jpeg/225px-Georg_Friedrich_Bernhard_Riemann.jpeg" alt="Riemann"></p>
  
  <p>Output image:<br />
  <img src="https://i.imgur.com/zEQew.png" alt="Output"></p>