Convert RGB to black OR white

Scaling to Black and White Convert to grayscale and then scale to white or black (whichever is closest). Original: Result: Pure Pillow implementation Install pillow if you haven’t already: $ pip install pillow Pillow (or PIL) can help you work with images effectively. from PIL import Image col = Image.open(“cat-tied-icon.png”) gray = col.convert(‘L’) bw = … Read more

how to save a pylab figure into in-memory file which can be read into PIL image?

Remember to call buf.seek(0) so Image.open(buf) starts reading from the beginning of the buf: import io from PIL import Image import matplotlib.pyplot as plt plt.figure() plt.plot([1, 2]) plt.title(“test”) buf = io.BytesIO() plt.savefig(buf, format=”png”) buf.seek(0) im = Image.open(buf) im.show() buf.close()

How do you composite an image onto another image with PIL in Python?

This can be accomplished with an Image instance’s paste method: from PIL import Image img = Image.open(‘/path/to/file’, ‘r’) img_w, img_h = img.size background = Image.new(‘RGBA’, (1440, 900), (255, 255, 255, 255)) bg_w, bg_h = background.size offset = ((bg_w – img_w) // 2, (bg_h – img_h) // 2) background.paste(img, offset) background.save(‘out.png’) This and many other PIL … Read more

PIL Convert PNG or GIF with Transparency to JPG without

Make your background RGB, not RGBA. And remove the later conversion of the background to RGB, of course, since it’s already in that mode. This worked for me with a test image I created: from PIL import Image im = Image.open(r”C:\jk.png”) bg = Image.new(“RGB”, im.size, (255,255,255)) bg.paste(im,im) bg.save(r”C:\jk2.jpg”)

tech