[SciPy-User] overflow

Nathaniel Smith njs@pobox....
Sat Jul 10 17:52:53 CDT 2010


On Sat, Jul 10, 2010 at 1:21 PM, Mr Nilsson <super.inframan@gmail.com> wrote:
> Hey
> Im working on a photo processing tool using numpy arrays to store the
> pixel data. I am currently in the process of adding 8 and 16bit
> support to my system in addition to float32.
> The problem is that when working with uint8 and uint16 numpy overflows
> the values of my pixels when I for example multiply (brighten) an
> image, making bright pixels dark again.
>
> Is there a way to have numpy clip the values to the maximum value of
> whatever dtype is used instead of overflowing?

You could do it manually (not tested):

def uint_saturating_multiply(image, gain):
  type_info = np.iinfo(image.dtype)
  assert type_info.kind == "u"
  # Find smallest number n such that n * gain will overflow:
  min_clipping = (long(type_info.max) + gain) // gain
  clip_mask = image >= min_clipping
  result = image * gain
  result[clip_mask] = type_info.max
  return result

-- Nathaniel


More information about the SciPy-User mailing list