【问题标题】:Converting image to black and white and use it as array将图像转换为黑白并将其用作数组
【发布时间】:2012-07-31 10:16:53
【问题描述】:

我正在尝试将彩色图像转换为黑白图像。

原图如下:

我有几个问题。第一:

import pylab as pl
import Image

im = Image.open('joconde.png')

pl.imshow(im)
pl.axis('off')
pl.show()

我明白了:

为什么要旋转?这不是重点,但我想知道原因。

im_gray = im.convert('1')

pl.imshow(im_gray)
pl.show() 

这是处理后的黑白图像:

现在一切正常。但是我需要将该图像用作 numpy 数组来进行一些图像处理。我所要做的就是:

import numpy as np

im_arr = np.array(im_gray)

pl.imshow(im_arr)
pl.axis('off')
pl.show()

但我明白了:

为什么会这样?我也试过了:

im_arr = np.array(im_gray, dtype='float')

或:

im_arr = np.asarray(im_gray)

但似乎没有任何效果。也许问题出在show 方法上,但我不知道。

【问题讨论】:

  • 你的图片没有旋转,它是垂直翻转的。

标签: python image image-processing computer-vision


【解决方案1】:

由于原点问题,您的图像被旋转。

如果你使用这个sn-p,图像不会倒转。

pl.imshow(im, origin='lower')
pl.show()

您也可以简单地使用im.show() 来显示图像。

现在,回到最初的问题。我认为问题出在 pylab 无法处理双层图像这一事实。您当然想使用灰度图像,因此这样做

import pylab as pl
import matplotlib.cm as cm
import numpy as np
import Image

im = Image.open('your/image/path')
im_grey = im.convert('L') # convert the image to *greyscale*
im_array = np.array(im_grey)
pl.imshow(im_array, cmap=cm.Greys_r)
pl.show() 

【讨论】:

    【解决方案2】:

    问题在于您将图像转换为 numpy 数组的方式。如果你看看函数的输出是什么,这就很清楚了

    >> np.array(im_gray)
    array([[False, False, False, ...,  True, False, False],
       [ True,  True,  True, ...,  True,  True, False],
       [ True,  True,  True, ...,  True,  True, False],
       ..., 
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], dtype=bool)
    

    这不可能。 pl.imshow 采用 floats uint8PIL 图像数组,而不是布尔数组。因此,您需要更明确地转换为数组,确保

    cols,rows = im_gray.size
    pixels = list(im_gray.getdata())
    
    # an indexer into the flat list of pixels
    # head ranges from 0 to len(pixels) with step cols
    # tail ranges from cols to len(pixels) with step cols
    head_tail = zip(range(0,len(pixels)+1,cols),range(cols,len(pixels)+1,cols))
    im_data = np.ndarray(shape=(cols,rows), dtype=np.uint8)
    
    # extract each row of pixels and save it to the numpy array
    for i,(head,tail) in enumerate(head_tail):
        im_data[i] = np.array(pixels[head:tail], dtype=np.uint8)
    
    pl.imshow(im_data, cmap='bone')
    

    最后的pl.imshow 要求您定义一个颜色图。 'bone' 颜色图是黑白的。我假设将PIL 图像传递给函数会自动定义颜色图。

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 2013-04-21
      • 2021-02-27
      • 2021-02-26
      • 1970-01-01
      • 2011-02-15
      相关资源
      最近更新 更多