2011-03-02 47 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',它应该是罚款。

相关问题