728x90
반응형
Python pillow, PIL.image 를 활용해서
가장 많이 사용된 색깔과
가운데 사용된 색깔을 추출해보자
우선 Pillow library 설치
$ pip install Pillow
1. 가장 많이 사용된 색 추출
from PIL import Image
from collections import Counter
def get_most_used_color(image_path):
# Open the image using Pillow
image = Image.open(image_path)
# Convert the image to RGB mode (in case it's grayscale or has an alpha channel)
image = image.convert('RGB')
# Get the width and height of the image
width, height = image.size
# Flatten the pixels into a list
pixels = list(image.getdata())
# Count occurrences of each color
color_counter = Counter(pixels)
# Get the most common color and its count
most_common_color, count = color_counter.most_common(1)[0]
return most_common_color
if __name__ == "__main__":
image_path = "path/to/your/image.png"
most_used_color = get_most_used_color(image_path)
print("Most used color:", most_used_color)
2. 가운데 있는 색 추출
from PIL import Image
def get_center_color(image_path):
# Open the image using Pillow
image = Image.open(image_path)
# Convert the image to RGB mode (in case it's grayscale or has an alpha channel)
image = image.convert('RGB')
# Get the width and height of the image
width, height = image.size
# Calculate the coordinates of the center pixel
center_x = width // 2
center_y = height // 2
# Get the color of the center pixel
center_color = image.getpixel((center_x, center_y))
# Convert the RGB color to a hexadecimal color code
hex_color = "#{:02x}{:02x}{:02x}".format(center_color[0], center_color[1], center_color[2])
return hex_color
if __name__ == "__main__":
image_path = "path/to/your/image.png"
center_color = get_center_color(image_path)
print("Color of the center pixel:", center_color)
728x90
반응형
'Python' 카테고리의 다른 글
Python: Error handling # 에러를 어떻게 다룰지를 쉽게 파악해보자 (0) | 2023.09.09 |
---|---|
Python: 중첩 list comprehension # 이중 컴프리헨션 # itertools # chain (0) | 2023.08.09 |
Python: Declare variable in one line with list # 배열의 요소로 변수선언하기 (0) | 2023.04.01 |
Python: rsplit # 파일 확장자 명 떼어서 이름 붙이기 (0) | 2023.03.28 |
Python: moviepy # duration # 비디오 파일 재생시간 가져오기 (0) | 2023.03.25 |