ClusterImg.py

ClusterImg.py — Python Source, 1Kb

ファイルコンテンツ

# -*- coding: utf-8 -*-
# ClusterImg.py
import Image
 
def calcavr(clusterid, img, N):
    """ クラスタごとに (R,G,B) の平均を求める
    clusterid ... クラスタリング結果
    img ......... 元の画像 ('RGB')
    N ........... クラスタ数
"""
    R = [0] * N
    G = [0] * N
    B = [0] * N
    count = [0] * N
    pos = 0
    data = img.getdata()
    for x in list(clusterid):
        r, g, b = data[pos]
        R[x] += r
        G[x] += g
        B[x] += b
        count[x] += 1
        pos += 1
    clustavr = [(R[x]/count[x], G[x]/count[x], B[x]/count[x]) 
                                            for x in range(N)]
    return clustavr
 
def clusterimg(size, clusterid, clustavr):
    """ クラスタリングの結果をそれぞれのクラスタ内の平均値で色を付けて画像にする
    size ... 画像サイズ (width, height) のタプル
    clusterid ... クラスタリング結果
    clustavr .... 各クラスタの平均値(R,G,B)
"""
    cimg = Image.new('RGB', size)
    cdata = [clustavr[clusterid[i]] for i in range(size[0]*size[1])]
    cimg.putdata(cdata)
    return cimg