![pillow black and white pillow black and white](https://www.ikea.com/nl/en/images/products/fjalltimotej-cushion-white-black__0980761_pe815101_s5.jpg)
Img = ombuffer('L', (h,w), bytes(data))Īrr = np.fromfile(ifile, dtype=np.uint8, count=w*h) Mem = memoryview(data).cast('B', shape=)ĭata = int.from_bytes(byte, "big") * 0xFF import numpy as npĭata = np.random.randint(2, size=w*h*N, dtype=np.uint8).tobytes()ĭata = bytes() Note that in my real world application, I can have data for numerous images back-to-back in one binary file. Failing that, some of these solutions work and perform well for my needs. I will accept an answer over this one that, as per the question, tells Pillow to directly treat 1's as white and 0's as black. With the help of the answers, I have tested a number of solutions where I can modify my data to replace 1's with 255's. Palette = palette + *(768-len(palette))įor data in iter(partial(ifile.read, w*h), b''): Here is the code: def create_images_palette(): With thanks to the comment from pointing me to, I have used Palette's to tell Pillow directly to treat 0 as black, and 1 as white. Some of them are very fast as they are, so probably not much more performance to be gained.īut IF there is a nice solution which avoids this overhead altogether, i.e.to tell Pillow directly to just treat 1's as white and 0's as black, that would be ideal. I have posted an answer with results of these solutions. With help of answers below, I have found a number of solutions where I can modify my data to replace 1's with 255's. Is there functionality within Pillow where it "just knows" that I want 1=white & 0=black (rather than 255=white & 0=black)? EDIT The problem is, the image is interpreting pixel data as grayscale, so a value of 1 is almost black. W = 128 # image could be much bigger, keeping it small for the exampleĭata = np.random.randint(2, size=w*h, dtype=np.uint8).tobytes()
#Pillow black and white code#
I want to create a black and white image from this data.Ī reproducible example of my code so far using Pillow in Python (note I would normally be loading the data from file rather than creating it in place): import numpy as np I have a binary file containing image pixel data consisting only bytes equal to 0 or 1 (0x00 or 0x01).