2011-03-02 52 views
-1

讓我使用一段代碼和一個更簡潔的描述。PIL + ndarrays如何才能在黑白模式下工作?

import numpy as np 
from PIL import Image as im 

real_img = im.open('test.jpg').convert('L') #comment the .convert('L') and it no longer works 
old_img = np.array(real_img) 
new_img = np.zeros(old_img.shape) 
for i_row in xrange(old_img.shape[0]): 
    for i_col in xrange(old_img.shape[1]): 
     new_img[i_row][i_col] = old_img[i_row][i_col] 
new_real_img = im.fromarray(new_img).convert('L') #comment the .convert('L') and it no longer works 
new_real_img.save('test2.jpg') 

此代碼只是需要的圖像,並試圖將它複製(在我的代碼,我做的還不止這些,但這是不夠的例子,因爲這說明我的問題)。如果你按原樣運行它(在同一文件夾中有一個名爲'test.jpg'的圖像),它就可以工作。但是,如果您刪除顯示的兩行上的convert('L'),則不再有效。我也無法將其轉換爲'RGB'或其他有用的格式。

所以這個問題似乎只要我使用彩色圖像,就不能使用PIL的ndarrays。有沒有辦法來解決這個問題?

回答

-1

Found this

「Image.fromarray()期望每像素一位,但實際上只有一個字節。」因此,儘管一切看起來都是平等的,但似乎轉換方法正在將數值轉化爲它們在引擎蓋下的二進制表示形式嗎?我不確定tbh。但是,這能解決問題:

import numpy as np 
from PIL import Image as im 

real_img = im.open('test.jpg') 
old_img = np.array(real_img) 
new_img = np.zeros(old_img.shape) 
for i_row in xrange(old_img.shape[0]): 
    for i_col in xrange(old_img.shape[1]): 
     new_img[i_row][i_col] = old_img[i_row][i_col] 
new_real_img = im.fromarray(new_img.astype('uint8')) 
new_real_img.save('test2.jpg') 

所以,要回圖像時,ndarray轉換爲'uint8',它應該是罰款。

相關問題