繁体   English   中英

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

[英]Converting image to black and white and use it as array

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

原始图像如下:

我有几个问题。 第一:

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

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

如果使用此代码段,则图像不会上下翻转。

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

问题在于您将图像转换为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图像传递到函数中以自动定义颜色图。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM