Skip to main content
 首页 » 编程设计

python之scipy.misc.imread flatten 参数——转换为灰度

2024年10月24日11qlqwjy

我试图了解此方法如何以灰度转换图像(如果它使用简单均值或加权均值)——我必须引用此方法。

来自documentation我知道这个方法调用了 convert('F') 方法。

来自 Pillow/PIL source code ,我可以找到这个方法,但是,当 mode 参数设置为“F”时,我找不到它的作用。

谢谢。

请您参考如下方法:

在 Image 对象的 convert 方法的文档字符串中(在您链接到的代码中看到),有​​这样的:

When translating a color image to black and white (mode "L"), the library uses the ITU-R 601-2 luma transform::

L = R * 299/1000 + G * 587/1000 + B * 114/1000

显然这也是 mode='F' 的处理方式。

这是一个例子:

In [2]: from PIL import Image 

为演示创建一个数组:

In [3]: x = np.random.randint(0, 9, size=(4, 4, 3)).astype(np.uint8) 

通过在 convert 方法中使用 mode='F' 将数组转换为图像并返回数组:

In [4]: np.array(Image.fromarray(x).convert('F')) 
Out[4]:  
array([[ 3.24499989,  6.30499983,  1.86899996,  4.54400015], 
       [ 3.54399991,  5.04300022,  4.63000011,  0.29899999], 
       [ 2.0539999 ,  3.29900002,  1.85800004,  1.76100004], 
       [ 3.9289999 ,  4.76100016,  5.76100016,  2.47799993]], dtype=float32) 

将 x 乘以 convert 的文档字符串中显示的因数:

In [5]: f = np.array([0.299, 0.587, 0.114]) 
 
In [6]: x.dot(f) 
Out[6]:  
array([[ 3.245,  6.305,  1.869,  4.544], 
       [ 3.544,  5.043,  4.63 ,  0.299], 
       [ 2.054,  3.299,  1.858,  1.761], 
       [ 3.929,  4.761,  5.761,  2.478]]) 

如果我们转换为 np.float32,我们会看到与 convert 方法创建的值完全相同:

In [7]: x.dot(f).astype(np.float32) 
Out[7]:  
array([[ 3.24499989,  6.30499983,  1.86899996,  4.54400015], 
       [ 3.54399991,  5.04300022,  4.63000011,  0.29899999], 
       [ 2.0539999 ,  3.29900002,  1.85800004,  1.76100004], 
       [ 3.9289999 ,  4.76100016,  5.76100016,  2.47799993]], dtype=float32)