찾다
백엔드 개발파이썬 튜토리얼색상 이론: 프로그래밍 방식으로 색상 활용

Color Theory: Playing with Colors Programmatically

처음 색상 팔레트 웹사이트인 Colorify Rocks를 구축하기 시작했을 때 프로그래밍 방식 색상 조작의 토끼굴이 얼마나 깊어질지 전혀 몰랐습니다. 단순한 "색상 선택기 만들기" 프로젝트로 시작된 것이 색상 이론, 수학적 색상 공간 및 접근성 고려 사항을 통한 매혹적인 여정으로 바뀌었습니다. 오늘은 여러분의 색상 모험에 도움이 될 수 있는 몇 가지 Python 코드와 함께 이 도구를 구축하면서 배운 내용을 공유하고 싶습니다.

단지 색상일 뿐인데, 얼마나 어려울 수 있나요?

아, 저를 지나쳤어요. 당신은 얼마나 순진했는가! 나의 여정은 사람들이 색상 팔레트를 생성하고 저장할 수 있는 웹사이트를 구축한다는 단순한 목표로 시작되었습니다. 쉽지요? 16진수 코드를 잡고... 잠깐, HSL이 뭐예요? 그리고 왜 RGB가 필요한가요? 그런데 CMYK가 도대체 ​​뭐죠?

내가 무슨 말을 하는지 보고 싶으신가요? #3B49DF

에 대한 색상 분석을 확인하세요.

색상 변환을 처리하기 위해 제가 작성한 첫 번째 코드는 다음과 같습니다. 이제 그 단순함에 웃음이 나옵니다.

class Color:
    def __init__(self, hex_code):
        self.hex = hex_code.lstrip('#')
        # Past me: "This is probably all I need!"
    def to_rgb(self):
        # My first "aha!" moment with color spaces
        r = int(self.hex[0:2], 16)
        g = int(self.hex[2:4], 16)
        b = int(self.hex[4:6], 16)
        return f"rgb({r},{g},{b})"

모든 것이 수학이다

그러다가 색상은 기본적으로 변장된 수학일 뿐이라는 사실을 깨달은 순간이 왔습니다. 색 공간 간 변환은 고등학교 이후로 접해본 적이 없는 알고리즘에 뛰어드는 것을 의미했습니다. 코드는 다음과 같이 발전했습니다.

def _rgb_to_hsl(self):
    # This was my "mind-blown" moment
    r, g, b = [x/255 for x in (self.rgb['r'], self.rgb['g'], self.rgb['b'])]
    cmax, cmin = max(r, g, b), min(r, g, b)
    delta = cmax - cmin
    # The math that made me question everything I knew about colors
    h = 0
    if delta != 0:
        if cmax == r:
            h = 60 * (((g - b) / delta) % 6)
        elif cmax == g:
            h = 60 * ((b - r) / delta + 2)
        else:
            h = 60 * ((r - g) / delta + 4)
    l = (cmax + cmin) / 2
    s = 0 if delta == 0 else delta / (1 - abs(2 * l - 1))
    return {
        'h': round(h),
        's': round(s * 100),
        'l': round(l * 100)
    }

색상에는 관계가 있습니다

Colorify Rocks를 위해 만든 가장 흥미로운 기능 중 하나는 색상 조화 생성기였습니다. 색상은 음표처럼 서로 관계가 있다는 것이 밝혀졌습니다! 색상 조화를 구현한 방법은 다음과 같습니다.

def get_color_harmonies(self, color):
    """
    This is probably my favorite piece of code in the entire project.
    It's like playing with a color wheel, but in code!
    """
    h, s, l = color.hsl['h'], color.hsl['s'], color.hsl['l']
    return {
        'complementary': self._get_complementary(h, s, l),
        'analogous': self._get_analogous(h, s, l),
        'triadic': self._get_triadic(h, s, l),
        'split_complementary': self._get_split_complementary(h, s, l)
    }
def _get_analogous(self, h, s, l):
    # The magic numbers that make designers happy
    return [
        self._hsl_to_hex((h - 30) % 360, s, l),
        self._hsl_to_hex(h, s, l),
        self._hsl_to_hex((h + 30) % 360, s, l)
    ]

접근성

색맹이 있는 사용자가 피드백을 제출했을 때 가장 놀랐습니다. 접근성을 완전히 간과했습니다! 이로 인해 색맹 시뮬레이션을 구현하게 되었습니다.

def simulate_color_blindness(self, color, type='protanopia'):
    """
    This feature wasn't in my original plan, but it became one of
    the most important parts of Colorify Rocks
    """
    matrices = {
        'protanopia': [
            [0.567, 0.433, 0],
            [0.558, 0.442, 0],
            [0, 0.242, 0.758]
        ],
        # Added more types after learning about different forms of color blindness
        'deuteranopia': [
            [0.625, 0.375, 0],
            [0.7, 0.3, 0],
            [0, 0.3, 0.7]
        ]
    }
    # Matrix multiplication that makes sure everyone can use our color palettes
    return self._apply_color_matrix(color, matrices[type])

Colorify Rocks가 성장함에 따라 디자이너들은 더 많은 기능을 요구하기 시작했습니다. 큰 것? 색상의 음영과 색조. 이로 인해 재미있는 실험이 이루어졌습니다.

def get_color_variations(self, color, steps=10):
    """
    This started as a simple feature request and turned into
    one of our most-used tools
    """
    return {
        'shades': self._generate_shades(color, steps),
        'tints': self._generate_tints(color, steps),
        'tones': self._generate_tones(color, steps)
    }

위 내용은 색상 이론: 프로그래밍 방식으로 색상 활용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
파이썬 : 편집과 해석에 대한 깊은 다이빙파이썬 : 편집과 해석에 대한 깊은 다이빙May 12, 2025 am 12:14 AM

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

루프 대 파이썬의 루프 : 주요 차이점 설명루프 대 파이썬의 루프 : 주요 차이점 설명May 12, 2025 am 12:08 AM

forloopsareideal when

루프를위한 것 및 기간 : 실용 가이드루프를위한 것 및 기간 : 실용 가이드May 12, 2025 am 12:07 AM

forloopsareusedwhendumberofitessiskNowninadvance, whilewhiloopsareusedwhentheationsdepernationsorarrays.2) whiloopsureatableforscenarioScontiLaspecOndCond

파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다파이썬 : 진정으로 해석 되었습니까? 신화를 파악합니다May 12, 2025 am 12:05 AM

pythonisnotpurelynlogreted; itusesahybrideprophorfbyodecodecompilationandruntime -INGRETATION.1) pythoncompilessourcecodeintobytecode, thepythonVirtualMachine (pvm)

동일한 요소를 가진 Python Concatenate 목록동일한 요소를 가진 Python Concatenate 목록May 11, 2025 am 12:08 AM

ToconcatenatelistsinpythonwithesameElements, 사용 : 1) OperatorTokeEpduplicates, 2) asettoremovedUplicates, or3) listComperensionForControlOverDuplicates, 각 methodHasDifferentPerferformanCeanDorderImpestications.

해석 대 컴파일 언어 : Python 's Place해석 대 컴파일 언어 : Python 's PlaceMay 11, 2025 am 12:07 AM

PythonisancerpretedLanguage, 비판적 요소를 제시하는 PytherfaceLockelimitationsIncriticalApplications.1) 해석 된 언어와 같은 thePeedBackandbackandrapidProtoTyping.2) CompilledlanguagesLikec/C transformt 해석

루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?루프를 위해 및 while 루프 : 파이썬에서 언제 각각을 사용합니까?May 11, 2025 am 12:05 AM

useforloopswhhenmerfiterationsiskNownInAdvance 및 WhileLoopSweHeniTesslationsDepoyConditionismet whilEroopsSuitsCenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTheLoopScenarioswhereTherInatismet, 유용한 광고 인 푸트 gorit

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)