user1573642
user1573642

Reputation: 41

PIL open.image & convert problems

The PIL Image.open.convert(L) give me a strange result :

   from PIL import Image

   test_img = Image.open('test.jpg').convert('L')

   imshow(test_img)

   show()
  1. it rotate the image (?)
  2. it doesn't convert it in L (?)

(sorry, I'm new so I cannot send images as demonstration)

Why (if you have an idea)?

Upvotes: 4

Views: 8568

Answers (2)

Balthazar Rouberol
Balthazar Rouberol

Reputation: 7180

Your image is rotated because of an origin inconsistency bewteen Image and pylab. If you use this snippet, the image will not be rotated upside-down.

import pylab as pl
import Image

im = Image.open('test.jpg').convert('L')
pl.imshow(im, origin='lower')
pl.show()

However, the image will not be displayed in black and white. To do so, you need to specify a greyscale colormap:

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

im = Image.open('test.jpg').convert('L')
pl.imshow(im, origin='lower', cmap=cm.Greys_r)
pl.show()

Et voilà!

Upvotes: 3

Nicolas Barbey
Nicolas Barbey

Reputation: 6797

The rotation is because the PIL and matplotlib don't use the same conventions. If you do an test_img.show() it will not rotate the image. Alternatively you can convert your image to a numpy array before display with matplotlib:

imshow(np.asarray(test_img))

As for the .convert('L') method, it works for me :

test_img = Image.open('test.jpg').convert('L')
print test_img.mode
# 'L'

Upvotes: 2

Related Questions