将图像转换为黑白并将其用作数组

时间:2012-07-31 10:16:53

标签: python image image-processing computer-vision

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

原始图片如下:

我有一些问题。第一:

import pylab as pl
import Image

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

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

我明白了:

First result

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

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方法中,但我不知道。

2 个答案:

答案 0 :(得分:3)

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

如果您使用此代码段,则图片不会颠倒旋转。

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() 

答案 1 :(得分: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图像传递给函数会自动定义颜色图。