Python: Greyscale image: Make everything white, except for black pixels
<p>I tried to open (already greyscale) images and change all non-black pixels to white pixels. I implemented the following code:</p>

<pre><code>from scipy.misc import fromimage, toimage
from PIL import Image
import numpy as np

in_path = 'E:\\in.png'
out_path = 'E:\\out.png'

# Open gray-scale image
img = Image.open(in_path).convert('L')

# Just for testing: The image is saved correct
#img.save(out_path)

# Make all non-black colors white
imp_arr = fromimage(img)
imp_arr = (np.ceil(imp_arr / 255.0) * 255.0).astype(int)

# Save the image
img = toimage(imp_arr, mode='L')
img.save(out_path)
</code></pre>

<p>The calculation to make all pixels white, except for the black ones is quite simple and also very fast. For my use-case it is especially important that it works very fast, for this reason i used numpy. For some reason this code does not work with all images?</p>

<p>An example: The following image is the input.</p>

<p><a href="http://i.stack.imgur.com/tQmM1.png" rel="nofollow"><img src="http://i.stack.imgur.com/tQmM1.png" alt="enter image description here"></a></p>

<p>It contains a grey rectangle and also a white border. The output should be a complete white image, but for some reason the output is a black image:</p>

<p><a href="http://i.stack.imgur.com/BY5Fc.png" rel="nofollow"><img src="http://i.stack.imgur.com/BY5Fc.png" alt="enter image description here"></a></p>

<p>With some other images it works quite well. What do i do wrong? I think floating point shouldn't be a big issue here, because this code does not require a high calculation accuracy to work.</p>

<p>Thank you very much</p>

<p><a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.toimage.html" rel="nofollow">toimage</a> expects a byte array, so convert to uint8 not int:</p>

<pre><code>imp_arr = (np.ceil(imp_arr / 255.0) * 255.0).astype('uint8')
</code></pre>

<p>I seems to work for <code>int</code> if there is a mix of black and white pixels in the output, but not if they are all white. I can't find any explanation for this in the documentation.</p>

python image performance