2013-01-01 182 views
5

我的目的:顯示灰度圖像

  1. 讀取的圖像進PIL格式。
  2. 將其轉換爲灰度。
  3. 使用pylab繪製圖像。

這裏是我使用的代碼:

from PIL import Image 
from pylab import * 
import numpy as np 

inputImage='C:\Test\Test1.jpg' 
##outputImage='C:\Test\Output\Test1.jpg' 

pilImage=Image.open(inputImage) 
pilImage.draft('L',(500,500)) 
imageArray= np.asarray(pilImage) 

imshow(imageArray) 

##pilImage.save(outputImage) 

axis('off') 

show() 

我的問題: 圖像獲取的喜歡的顏色顛倒顯示。

This is the Original Image

This is how it appears in the Python Window

但我知道,圖像越來越轉換爲灰度,因爲當我把它寫它的出現爲灰度圖像的磁盤。(正如我期望的那樣)。

我覺得問題是在numpy轉換的某個地方。

我剛剛開始使用Python進行圖像處理編程。 並提示和指導方針也將不勝感激。

回答

13

你想爲忽略默認的彩色地圖:

imshow(imageArray, cmap="Greys_r") 

Here's a page on plotting images and pseudocolor in matplotlib

+0

我嘗試這樣做。我得到一個灰度圖像,但它是一個倒置的灰度圖像。 –

+0

確定 - 更新了反色圖 – YXD

+0

這解決了我的問題。你能解釋我,這部分是做什麼,爲什麼它需要imshow()?或者,也許直接給我一個可以解釋這個問題的頁面。 –

2

這產生了乙&用黑白:

pilImage=Image.open(inputImage) 
pilImage = pilImage.convert('1') #this convert to black&white 
pilImage.draft('L',(500,500)) 

pilImage.save('outfile.png') 

convert方法docs

convert 

im.convert(mode) => image 

Returns a converted copy of an image. 
When translating from a palette image, this translates pixels through the palette. 
If mode is omitted, a mode is chosen so that all information in the image and the palette can be represented without a palette. 

When from a colour image to black and white, the library uses the ITU-R 601-2 luma transform: 

    L = R * 299/1000 + G * 587/1000 + B * 114/1000 
When converting to a bilevel image (mode "1"), the source image is first converted to black and white. 
Resulting values larger than 127 are then set to white, and the image is dithered. 
To use other thresholds, use the point method.