2

I am working with images in numpy and at some point I scale an image.

import scipy.misc        as msc
import numpy             as np
...
img_rgb = msc.imread(img_fn)
im_scaled = img_rgb * factor

The result sometimes looks ugly with bright regions showing black spots. This seems to be caused by numerical overflow of the 8bit image RGB pixel. Is there a way to apply a ceiling operator such that if the multiplication would be > 255 it is clipped to 255. (I am not interested in a floor function as I don't expect signal to become negative)

I know I can test every pixel in a loop, but the would not be following the numpy philosophy of array handling.

Any help is much appreciated.

Thanks, Gert

2 Answers 2

3

Use np.clip(x*float(factor), 0, 255).astype(np.uint8)

e.g.

x = np.array([120, 140], dtype=np.uint8)
factor = 2
result = np.clip(x*float(factor), 0, 255).astype(np.uint8)
> array([240, 255], dtype=uint8)

Note the float(factor) is important because if it is left as an int there will be overflow before the clip.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use numpy.clip(), it does exactely that.

However, the image is probably not going to be pretty either. Usually, what you want is to convert the image values from byte, in the range of [0,255], to float, in the range of [0,1] (even if implicitly), and apply gamma correction.

3 Comments

clip() doesn't really help with integer overflow. It is too late to clip after multiplying, because the overflow has already happened. You would have to upcast the input to, say, 16 bit integers or floating point, do the multiplication, and then clip.
@WarrenWeckesser clip before the multiply, ie scaled = img.clip(0, 255 // factor) * factor.
You commenters are right. That's why the implicit final advice, in the second paragraph, is to convert from byte to float, perform the operations, and only then convert back.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.