2013-08-16 231 views
0

我有一個png文件,我想刪除所有非黑色像素(將非黑色像素轉換爲白色)。 我怎麼能輕鬆地在Python中做到這一點?謝謝!Python - 刪除(轉換爲白色)圖像的非黑色像素

+2

http://en.wikipedia.org/wiki/Python_Imaging_Library – jeremy

+0

將它們轉換爲什麼? –

+0

將非黑色像素轉換爲白色,對此感到抱歉 –

回答

2

下面是與PIL做到這一點的一種方法:

from PIL import Image 

# Separate RGB arrays 
im = Image.open(file(filename, 'rb')) 
R, G, B = im.convert('RGB').split() 
r = R.load() 
g = G.load() 
b = B.load() 
w, h = im.size 

# Convert non-black pixels to white 
for i in range(w): 
    for j in range(h): 
     if(r[i, j] != 0 or g[i, j] != 0 or b[i, j] != 0): 
      r[i, j] = 255 # Just change R channel 

# Merge just the R channel as all channels 
im = Image.merge('RGB', (R, R, R)) 
im.save("black_and_white.png") 
+2

爲什麼不只是轉換爲L,那麼所有> 0都變爲1,然後轉換回來?這要簡單得多,而且可能會更快或更快(因爲它在C中而不是在Python中執行大循環)。 – abarnert

2

我這樣做是使用自造我的MAC,我不知道你用這樣的操作系統,我不能給你更具體的說明,但這些都是你需要,如果你還沒有做他們已經採取的一般步驟:

1)安裝的libjpeg(如果你要來處理一個.jpeg文件,PIL不來與此)

2)安裝pil(http://www.pythonware.com/products/pil/或通過自制或macports等如果您使用的是Mac)

3)鏈接PIL與Python如果需要

4)使用此代碼:

from PIL import Image 

img = Image.open("/pathToImage") # get image 
pixels = img.load() # create the pixel map 

for i in range(img.size[0]): # for every pixel: 
    for j in range(img.size[1]): 
     if pixels[i,j] != (0,0,0): # if not black: 
      pixels[i,j] = (255, 255, 255) # change to white 

img.show() 

隨意問發表評論,如果你得到的地方停留。

+0

您正在將所有黑色像素轉換爲白色。他需要將所有非黑色像素轉換爲白色。 –

+0

哦,哎呀,我一定有誤讀我會盡快解決 – Joohwan

相關問題