2011-12-28 101 views
1

給定具有正好22種顏色(每種具有不同RGB值)的圖像(.tiff或geotiff文件),有什麼方法將它們分離(「過濾」)爲22個單獨的圖像,每個只包含那些具有特定RGB值的像素?PIL?提取給定RGB值的所有像素

回答

4

這裏是做這件事的按像素的方式,可爲圖像中的任意數量的顏色搭配(儘管它可以得到很多的色彩和大圖像慢)。它也適用於調色板圖像(它將它們轉換)。

import Image 

def color_separator(im): 
    if im.getpalette(): 
     im = im.convert('RGB') 

    colors = im.getcolors() 
    width, height = im.size 
    colors_dict = dict((val[1],Image.new('RGB', (width, height), (0,0,0))) 
         for val in colors) 
    pix = im.load()  
    for i in xrange(width): 
     for j in xrange(height): 
      colors_dict[pix[i,j]].putpixel((i,j), pix[i,j]) 
    return colors_dict 

im = Image.open("colorwheel.tiff") 
colors_dict = color_separator(im) 
#show the images: 
colors_dict.popitem()[1].show() 
colors_dict.popitem()[1].show() 
  1. 調用im.getcolors()返回圖像中的所有顏色的列表和它們發生的次數,作爲一個元組,除非顏色數超過最大值(您可以指定,默認到256)。
  2. 我們然後建立一個辭典colors_dict,通過圖像中的顏色鍵,以及與空對應的圖像的值。
  3. 然後我們遍歷所有像素的圖像,更新每個像素的適當的字典項。像這樣做,意味着我們只需要通讀一次圖像。我們使用load()使像素訪問速度更快,因爲我們通過圖像讀取。
  4. color_separator()返回圖像的詞典,通過圖像中的每個獨特的顏色鍵。

爲了讓它更快一點,你可以在colors_dict使用load()每一個形象,但你可能需要小心一點,因爲它會消耗大量的內存,如果圖像有很多顏色和大。如果這不是一個問題,再加入(後創作的colors_dict):

fast_colors = dict((key, value.load()) for key, value in colors_dict.items()) 

和交換:

colors_dict[pix[j,i]].putpixel((j,i), pix[j,i]) 

爲:

fast_colors[pix[j,i]][j,i] = pix[j,i] 

22彩色圖像:enter image description here

22顏色分離的圖像:

enter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description hereenter image description here enter image description hereenter image description hereenter image description hereenter image description hereenter image description here enter image description hereenter image description hereenter image description hereenter image description here

+0

那麼,你將如何結合幾個22倍的圖像,比如,黃色和紅色的的?或者至少沒有圖像中的黑色來允許將22張圖像中的少數圖像粘貼到新圖像中? – klocey 2013-04-19 23:28:36