2017-01-02 20 views
2

我有一個二進制圖像,尺寸64x63,每一個像素是1或0。Python翻轉二進制圖像; .invert()失敗

import struct 
from PIL import Image 
import numpy 

... 

i1 = Image.frombytes('1', (64, 63), r[3], 'raw') 

如何可以反轉該圖像?

編輯

我試圖建議的解決方案:

from PIL import Image 
import PIL.ImageOps  

i1 = PIL.ImageOps.invert(i1) 

然而,這導致了錯誤:

raise IOError("not supported for this image mode") 
IOError: not supported for this image mode 

而這一點,我相信,這是由於這樣的事實圖像既不是RGB也不是L(灰度)。相反,它是一個二進制圖像文件,其中每個像素只有0或1

+0

[如何用PIL(Python-Imaging)反轉圖像顏色的可能重複?](http://stackoverflow.com/questions/2498875/how-to-invert-colors-of-image-with-pil -python-imaging) – 9000

+0

如有疑問,請先google。 – 9000

+0

感謝您的建議!但是,我確實嘗試過,儘管我從PIL收到一個錯誤,指出不支持二進制圖像。 – wayway

回答

1

如果你願意i1轉換爲numpy的數組你可以做

i1 = 1 - numpy.asarray(i1) 
+0

看起來i1不是numpy數組。我正在使用Image.frombytes創建i1。使用代碼i1 = 1 - i1,我收到錯誤:TypeError:不支持的操作數類型爲 - :'int'和'圖像' – wayway

+1

@WayWay我編輯了代碼來處理這個問題。如果您需要繼續使用Pillow'Image'對象,則可以在 – bobo

-1
from PIL import Image 
import PIL.ImageOps  

image = Image.open('your_image.png') 

inverted_image = PIL.ImageOps.invert(image) 

inverted_image.save('your_image_inv.png') 
+0

之後使用'Image.fromarray(i1)'您的答案可能是正確的,但可以通過添加對代碼的解釋以及爲什麼應該使用它。 – Mikkel

0

我來了跨越完全相同的問題。有一個解決方案,而不會使用numpy的麻煩。
您可以使用ImageMath

from PIL import ImageMath 
i2 = ImageMath.eval('255-(a)',a=i1) 

這樣就可以(在PIL模式1)反轉的二進制圖像。
有關ImageMath的更多信息,請參閱here