본문 바로가기

Python

Python: 색 추출 # pick color # PIL

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
반응형