2014-12-05 417 views
0

我試圖將array轉換爲壓縮的圖像(tif)(它將在另一端取消)。不過,我在下跌的第一道關卡......使用Pillow在Python中將數組轉換爲圖像(tif)

我有以下幾點:

pillow_image = Image.fromarray(image_data) 

這給了我這個錯誤:

File "/Users/workspace/test-app/env/lib/python2.7/site-packages/PIL/Image.py", 

line 2155, in fromarray arr = obj.array_interface AttributeError: 'tuple' object has no attribute 'array_interface'

什麼我我錯在這裏做?

回答

2

image_data是4個numpy數組的元組,每個(可能)形狀(H,W)。你 需要image_data是一個形狀(H,W,4)的單個陣列。因此,請使用np.dstack來組合通道。

至少有一個數組有dtype int32。但要將其用作8位色彩通道,陣列需要爲dtype uint8(因此最大值爲255)。您可以使用astype將陣列轉換爲dtype uint8。希望你的數據不包含大於255的值。如果是這樣,astype('uint8')將只保留最低有效位(即返回模256的數)。

image_data = np.dstack(image_data).astype('uint8') 
pillow_image = Image.fromarray(image_data) 
+0

感謝您提供這樣的信息答案。它很容易再次覆蓋它? – Prometheus 2014-12-05 19:38:36

+0

我不確定你的意思是「封面」。如果你的意思是再次將它分成4個單獨的數組,那麼你可以使用'arr = np.array(pillow_image)'和'r,g,b,a = arr [...,0],arr [.. ...,1],arr [...,2],arr [...,3]'。 – unutbu 2014-12-05 20:03:41

+0

對不起,我的意思是再次將它們轉換回4個數組。我可以從鏈接中看到你發佈了一些很好的例子。謝謝 – Prometheus 2014-12-05 20:06:29

相關問題