KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
For an image processing class, I am doing point operations on monochrome images. Pixels are uint8 [0,255]. numpy uint8 will wrap. For example, 235+30 = 9. I need the pixels to saturate (max=255) or truncate (min=0) instead of wrapping. My solution uses int32 pixels for the point math then converts to uint8 to save the image. Is this the best way? Or is there a faster way? #!/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" ) Input image: Output image:
Tags (comma-separated)
Save Edits
Cancel