Scipy.misc.imread flatten argument — converting to grey scale

耗尽温柔 提交于 2021-01-28 01:50:21

问题


I'm trying to understand how this method transform an image in grey scale (if it uses a simple mean or a weighted mean) -- I have to reference this method.

From the documentation I know that this method calls the convert(‘F’) method.

From Pillow/PIL source code, I can find this method, however, I couldn't find what it does when the mode parameter is set to 'F'.

Thank you.


回答1:


In the docstring of the convert method of the Image object (seen in the code that you linked to), there is this:

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

Apparently this is also how mode='F' is handled.

Here's an example:

In [2]: from PIL import Image

Create an array for the demonstration:

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

Send the array through the conversion to an Image and back to an array, using mode='F' in the convert method:

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)

Multiply x by the factors shown in the docstring of 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]])

If we convert to np.float32, we see exactly the same values as created by the convert method:

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)



回答2:


The mode parameter 'F' stands for 'floating point'.

from PIL import Image

im = Image.new("F", (2,2))
pixels = im.load()
pixels[0,0] = 255.0
pixels[1,0] = 200.0
pixels[0,1] = 100.0
pixels[1,1] = 20.0
im.show()


来源:https://stackoverflow.com/questions/32314657/scipy-misc-imread-flatten-argument-converting-to-grey-scale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!