Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python invert binary image; .invert() fails

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.

like image 334
waylonion Avatar asked Jan 02 '17 03:01

waylonion


3 Answers

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') )
like image 76
hamish Avatar answered Sep 30 '22 10:09

hamish


If you're willing to convert i1 to a numpy array you can just do

i1 = 1 - numpy.asarray(i1)
like image 20
bobo Avatar answered Sep 30 '22 10:09

bobo


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.

like image 35
Amen Avatar answered Sep 30 '22 08:09

Amen