Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Scaling to Black and White</h1> <p>Convert to grayscale and then scale to white or black (whichever is closest).</p> <p>Original:</p> <p><img src="https://i.stack.imgur.com/H334L.png" alt="meow meow tied up cat"></p> <p>Result:</p> <p><img src="https://i.stack.imgur.com/muT5j.png" alt="Black and white Cat, Pure"></p> <h2>Pure Pillow implementation</h2> <p>Install <code>pillow</code> if you haven't already:</p> <pre><code>$ pip install pillow </code></pre> <p><a href="https://github.com/python-imaging/Pillow">Pillow</a> (or PIL) can help you work with images effectively.</p> <pre><code>from PIL import Image col = Image.open("cat-tied-icon.png") gray = col.convert('L') bw = gray.point(lambda x: 0 if x&lt;128 else 255, '1') bw.save("result_bw.png") </code></pre> <p>Alternatively, you can use <a href="https://github.com/python-imaging/Pillow">Pillow</a> with <a href="http://www.numpy.org/">numpy</a>. </p> <h2>Pillow + Numpy Bitmasks Approach</h2> <p>You'll need to install numpy:</p> <pre><code>$ pip install numpy </code></pre> <p>Numpy needs a copy of the array to operate on, but the result is the same.</p> <pre><code>from PIL import Image import numpy as np col = Image.open("cat-tied-icon.png") gray = col.convert('L') # Let numpy do the heavy lifting for converting pixels to pure black or white bw = np.asarray(gray).copy() # Pixel range is 0...255, 256/2 = 128 bw[bw &lt; 128] = 0 # Black bw[bw &gt;= 128] = 255 # White # Now we put it back in Pillow/PIL land imfile = Image.fromarray(bw) imfile.save("result_bw.png") </code></pre> <h1>Black and White using Pillow, with dithering</h1> <p>Using <a href="https://github.com/python-imaging/Pillow">pillow</a> you can convert it directly to black and white. It will look like it has shades of grey but your brain is tricking you! (Black and white near each other look like grey)</p> <pre><code>from PIL import Image image_file = Image.open("cat-tied-icon.png") # open colour image image_file = image_file.convert('1') # convert image to black and white image_file.save('/tmp/result.png') </code></pre> <p>Original:</p> <p><img src="https://i.stack.imgur.com/mvvu0.png" alt="meow meow color cat"></p> <p>Converted:</p> <p><img src="https://i.stack.imgur.com/LsIJ0.png" alt="meow meow black and white cat"></p> <h1>Black and White using Pillow, without dithering</h1> <pre><code>from PIL import Image image_file = Image.open("cat-tied-icon.png") # open color image image_file = image_file.convert('1', dither=Image.NONE) # convert image to black and white image_file.save('/tmp/result.png') </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload