홈페이지 제작 후 다시배우는 FastApi

경환오·2021년 10월 26일
0

백엔드공부!

목록 보기
1/4

생각해보면 무작정 홈페이지가 만들고 싶었고 Python을 좋아해서 그냥 만들었다.

https://coloravg.run.goorm.io/

디자인도 지금보면.. 할많하않

그래서 지금부터 다시 공부하려고 한다. 하나하나 이유를 생각해보려한다 수업에서 확실히 '이유'가 있어야 열심히 했고 지금도 똑같다 이렇게 블로그 글을 쓰는 것도 이유가 있기때문이다.

그래도 처음 포스트니까 하나의 팁은 적고 가려고한다.

RGBtoHSVtoXYZ

처음보면 이게 무슨 말인가 싶을것이다. 그도 그런게 나도 단순히 opencv에서 rgb받아서 평균색상이나 색상비교를 하면 잘될 것이라 생각했는데. RGB에서 추출한 평균, HSV추출한 평균 그러한 값들을 다른 값과 비교하는 과정 이런것을 하다보니 HSV conic모델로 정하고 XYZ좌표를 만들어서 비교하는게 최고하는 것이다. 다른 방법도 전부 비교했지만 이게 최고이다.

opencv를 일딴 받았다면

import pandas as pd
import math


data = pd.read_csv("color-rgb.csv")
RGB = data.iloc[:, 3:]
RGB = RGB.apply(lambda x: x.astype(str).map(lambda x: int(x, base=16)/255.0))
RGB["v"] = RGB.max(axis=1)
RGB["m"] = RGB.min(axis=1)
RGB["h"] = ""
RGB["s"] = ""
for i in range(len(RGB)):
    if RGB["v"][i] == 0:
        RGB["s"][i] = 0
        RGB["h"][i] = 0
    else:
        RGB["s"][i] = 1 - (RGB["m"][i] / RGB["v"][i])
        if RGB["v"][i] == RGB["R"][i]:
            RGB["h"][i] = 60 * (RGB["G"][i] - RGB["B"][i]) / (RGB["v"][i] - RGB["m"][i])
        elif RGB["v"][i] == RGB["G"][i]:
            RGB["h"][i] = 120 + (60 * (RGB["B"][i] - RGB["R"][i])) / (RGB["v"][i] - RGB["m"][i])
        elif RGB["v"][i] == RGB["B"][i]:
            RGB["h"][i] = 240 + (60 * (RGB["R"][i] - RGB["G"][i])) / (RGB["v"][i] - RGB["m"][i])
        if RGB["h"][i] < 0:
            RGB["h"][i] += 360
        RGB["h"][i] /= 360
        RGB["h"][i] *= 255

RGB["s"] = RGB["s"].apply(lambda x: int(x*255))
RGB["v"] = RGB["v"].apply(lambda x: int(x*255))
RGB = RGB.fillna(0)
RGB["h"] = RGB["h"].apply(lambda x: int(x))
HSV = RGB[["h", "s", "v"]]
HSV["x"] = ""
HSV["y"] = ""
HSV["z"] = ""
for i in range(len(HSV)):
    HSV["x"][i] = HSV["s"][i]*math.cos(2*math.pi*HSV["h"][i]/255)
    HSV["y"][i] = HSV["s"][i]*math.sin(2*math.pi*HSV["h"][i]/255)

HSV["z"] = HSV["v"]

HSV = pd.concat([data["name"], HSV], axis=1)
print(HSV)
HSV.to_csv("color-hsv-xyz.csv")

핵심은 HSV로 어찌 변환을 하는가 이다. 이것은 공식이 이미 존재하기 때문에 바로 적용했다.

from sklearn.cluster import KMeans
import numpy as np
import cv2
import math
import pandas as pd

color = pd.read_csv("HSV.csv")
color_rgb = pd.read_csv("color-rgb.csv")
analysis = pd.read_csv("Analysis.csv", index_col=0)

def avg_color(img):
    encoded_img = np.fromstring(img, np.uint8)
    image = cv2.imdecode(encoded_img, cv2.IMREAD_COLOR)
    image = cv2.resize(image, dsize=(640, 480), interpolation=cv2.INTER_AREA)
    #image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
    image = image.reshape((image.shape[0] * image.shape[1], 3)) #HSV이미지를 색상의 한줄 조합으로 가져오는 부분
    k = 4
    colorlist_all = []
    clt = KMeans(n_clusters=k)
    clt.fit(image)
    print(image.shape)
    i = 0
    for center in clt.cluster_centers_[0:4]:
        i += 1
        print(center)
        center[0] = center[0]/255.0
        center[1] = center[1]/255.0
        center[2] = center[2]/255.0
        v = max(center)
        m = min(center)
        print(v)
        if v == 0:
            s = 0
            h = 0
        else:
            s = 1 - m/v
            if v == center[2]:
                h = 60 * (center[1] - center[0]) / (v - m)
            elif v == center[1]:
                h = 120 + (60 * (center[0] - center[2])) / (v - m)
            elif v == center[0]:
                h = 240 + (60 * (center[2] - center[1])) / (v - m)
            if h < 0:
                h += 360
            h /= 360
            h *= 255
        s = s*255
        v = v*255
        x = s*math.cos(2*math.pi*h/255)*v/255
        y = s*math.sin(2*math.pi*h/255)*v/255
        z = v
        df_min = 1000
        for color_c in range(len(color)):
            df_c = math.sqrt(
                (x-color["x"][color_c])**2 +
                (y-color["y"][color_c])**2 +
                (z-color["z"][color_c])**2
            )
            if df_min > df_c:
                df_min = df_c
                df_min_f = color_c
        print(color["name"][df_min_f])
        print(color_rgb["RGB"][df_min_f])
        colordict = {
            "name": color["name"][df_min_f],
            "code": color_rgb["RGB"][df_min_f],
            "tone": color["tone"][df_min_f],
            "base": color["base"][df_min_f]
        }
        colorlist_all.append(colordict)
    return colorlist_all

이게 핵심이다. xyz를 따로 구해야 좀더 우리가 눈으로 확인하는 색의 비슷함과 유사해진다.

그러면 질문은 아래에서 받고 저는 다시 공부하러 가겠습니다.

ex)

위의 식을 이용해서 의류에서 평균색 4가지를 추출한 모습이다.

면접 떨어지고 확실히 나의 수준을 더욱 알게되어서 열심히 하게된다.!

profile
방문해주셔서 감사합니다!

0개의 댓글