Convert an image to black and white and use it as an array

I am trying to convert a color image to black and white.

The original image is as follows:

I have a few issues. Firstly:

import pylab as pl
import Image

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

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

I get this:

First result

Why is he spinning? This is not a question, but I would like to know why.

im_gray = im.convert('1')

pl.imshow(im_gray)
pl.show() 

And here is the processed black and white image:

Now everything looks working. But I need to use this image as a numpy array to do some image processing. All I need to do is the following:

import numpy as np

im_arr = np.array(im_gray)

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

But I get this:

Why is this happening? I also tried:

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

or

im_arr = np.asarray(im_gray)

But nothing works. Perhaps the problem lies in the method show, but I do not know.

+5
source share
2 answers

- .

, .

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

, 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 uint8 PIL , . , ,

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 .

+2

All Articles