I have a binary image, dimensions 64x63 where every pixel is a 1 or 0.
import struct
from PIL import Image
import numpy
...
i1 = Image.frombytes('1', (64, 63), r[3], 'raw')
How can I invert this image?
Edit
I attempted the suggested solution:
from PIL import Image
import PIL.ImageOps
i1 = PIL.ImageOps.invert(i1)
However, this resulted in the error:
raise IOError("not supported for this image mode")
IOError: not supported for this image mode
And this, I believe, is due to the fact that the image is neither RGB nor L(greyscale). Instead, it is a binary image file where each pixel is only either 0 or 1.
Another option is to convert the image to a supported inversion format, before inverting it, ie:
import PIL.ImageOps
inverted_image = PIL.ImageOps.invert( image.convert('RGB') )
If you're willing to convert i1
to a numpy array you can just do
i1 = 1 - numpy.asarray(i1)
I came across the exact same problem. There is a solution without going to the trouble of using numpy.
you can use ImageMath
:
from PIL import ImageMath
i2 = ImageMath.eval('255-(a)',a=i1)
This way you can invert a binary (mode 1 in PIL) image.
For more an ImageMath refer to here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With