CORDEA blog

Android applications engineer

【Python】画像の寒色・暖色を判定するプログラム

画像の寒色・暖色を判断するプログラムというのはあまり無いので書いてみた。

stackoverflowの投稿をもとに、rgb -> hsv に変換し、hの範囲で判断する。
結局のところ、どこまでの寒色・暖色とするかは用途や人によって違うと思うので、とりあえずパーセンテージで出力。
いくつか試してみたけど予想以上に上手く行っているので驚いた。

#!/usr/bin/env python
# encoding:utf-8
#
# Copyright [2015] [Yoshihiro Tanaka]
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

__Author__ =  "Yoshihiro Tanaka <contact@cordea.jp>"
__date__   =  "2015-05-16"

from PIL import Image
import sys, colorsys

def main(filename):
    image = Image.open(filename)

    width, height = image.size
    pixel = image.load()

    data = []
    for w in range(width):
        for h in range(height):
            r, g, b = [r/255.0 for r in pixel[w, h]]
            data.append((colorsys.rgb_to_hsv(r, g, b)[0])*255.0)
    
    warmcool = [0, 0]
    for h in data:
        if 0 <= h <= 80 or 330 <= h <= 360:
            warmcool[0] += 1
        else:
            warmcool[1] += 1

    per = (warmcool[0] / float(sum(warmcool))) * 100
    print("warm: %f %%" % per)

if __name__=='__main__':
    main(sys.argv[1])