2011-12-28 4 views

답변

4

이미지의 색상 수에 관계없이 픽셀 단위로 작업 할 수 있습니다 (많은 색상과 큰 이미지에서 느려질 수 있음). 또한 paletted 이미지 (그것은 그들을 변환) 작동합니다.

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 색 격리 된 이미지 :

(210)

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

관련 문제