1. ColorThief
PIL, python을 기반으로 하고 있는 모듈로 특정 이미지 내 color palette를 추출하거나 대표 컬러를 추출할 수 있음.
설치 방법은 아래 PIP 명령어 참고
$pip install colorthief
사용법은 아래와 같다
ColorThief 설치 후, 이미지를 colorthief 객체에 넣어준다.
get_color 함수와 get_palette함수로 원하는 컬러를 얻어온다.
각 함수에 대한 자세한 설명은 다음 링크를 참고하자.
GitHub - fengsp/color-thief-py: Grabs the dominant color or a representative color palette from an image. Uses Python and Pillow
Grabs the dominant color or a representative color palette from an image. Uses Python and Pillow. - GitHub - fengsp/color-thief-py: Grabs the dominant color or a representative color palette from a...
github.com
간단하게 get_color는 가장 지배적인 컬러하나를 return하고, quality가 1일수록 가장 정답에 가깝게 뽑아낸다.
(화려한 이미지에서 quality를 1로 놓고 추출할 경우, 처리 속도가 느릴 수 있는데 이 처리속도를 해결하기 위한 방법 / 10, 100, 값이 커지면 커질수록 빨리 return한다고 하지만, 퀄리티는 보장하지 X)
get_palette는 원하는 컬러 개수대로 구성하는 컬러 파레트를 추출해준다.
아래는 샘플 코드다.
from colorthief import ColorThief
import matplotlib.pyplot as plt
color_thief = ColorThief("./test.png")
# get the dominant color
dominant_color = color_thief.get_color(quality=1)
# dominant_color는 (R, G, B)로 구성된 3 x 1 tuple을 return
palette = color_thief.get_palette(color_count=3)
# palette 는 N개의 컬러를 list에 담아 return
print(dominant_color)
#(111, 195, 227)
print(palette)
#[(20, 17, 21), (111, 195, 227), (194, 81, 78), (91, 145, 145)]
plt로 시각화 해보면 다음과 같은 것을 확인할 수 있다
근데 나는 특정 이미지 path가 아니라 코드 내에서 발생한 image 객체(like 일부 영역만 crop한 image)로부터 palette를 추출하고 싶었다.
다른 방식을 찾아보니 아래 패키지가 더 활용성면에서 좋다는 것을 발견했다.
2. ExtColors
동일하게 pip로 패키지를 다운받는다
$ pip install extcolors
상세한 코드는 하단 github 에서 참고하면 되고, 아까와 동일하게 palette를 추출할 수 있다.
GitHub - CairX/extract-colors-py: Extract colors from an image. Colors are grouped based on visual similarities using the CIE76
Extract colors from an image. Colors are grouped based on visual similarities using the CIE76 formula. - GitHub - CairX/extract-colors-py: Extract colors from an image. Colors are grouped based on ...
github.com
# 이미지 경로로 전달할 때
palette = extcolors.extract_from_image(bg_path, tolerance = 12, limit = 6)
# 이미지 객체로 전달할 때
colors, pixel_count = extcolors.extract_from_image(img)
참고자료 :
https://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image
Python - Find dominant/most common color in an image
I'm looking for a way to find the most dominant color/tone in an image using python. Either the average shade or the most common out of RGB will do. I've looked at the Python Imaging library, and c...
stackoverflow.com
https://towardsdatascience.com/image-color-extraction-with-python-in-4-steps-8d9370d9216e
Image Color Extraction with Python in 4 Steps
Creating your own and unique list of colors
towardsdatascience.com