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

blu*_*fer 5 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()
Run Code Online (Sandbox Code Playgroud)

我明白了:

第一个结果

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

im_gray = im.convert('1')

pl.imshow(im_gray)
pl.show() 
Run Code Online (Sandbox Code Playgroud)

这是处理过的黑白图像:

现在一切看起来都有效 但我需要将该图像用作numpy数组,以便进行一些图像处理.我所要做的就是:

import numpy as np

im_arr = np.array(im_gray)

pl.imshow(im_arr)
pl.axis('off')
pl.show()
Run Code Online (Sandbox Code Playgroud)

但我明白了:

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

im_arr = np.array(im_gray, dtype='float')
Run Code Online (Sandbox Code Playgroud)

要么:

im_arr = np.asarray(im_gray)
Run Code Online (Sandbox Code Playgroud)

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

Bal*_*rol 6

由于原点问题,您的图像发生了旋转。

如果您使用此片段,图像将不会颠倒旋转。

pl.imshow(im, origin='lower')
pl.show()
Run Code Online (Sandbox Code Playgroud)

您也可以简单地用于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() 
Run Code Online (Sandbox Code Playgroud)