﻿import cv2
import numpy as np
import glob
import os

def rgb2lab(inputColor):
    num = 0
    RGB = [0, 0, 0]
    for value in inputColor:
        value = float(value) / 255
        if value > 0.04045:
            value = ((value + 0.055) / 1.055) ** 2.4
        else:
            value = value / 12.92
        RGB[num] = value * 100
        num = num + 1
    XYZ = [0, 0, 0,]
    X = RGB[0] * 0.4124 + RGB[1] * 0.3576 + RGB[2] * 0.1805
    Y = RGB[0] * 0.2126 + RGB[1] * 0.7152 + RGB[2] * 0.0722
    Z = RGB[0] * 0.0193 + RGB[1] * 0.1192 + RGB[2] * 0.9505
    XYZ[0] = float(X) / 95.047         
    XYZ[1] = float(Y) / 100.0          
    XYZ[2] = float(Z) / 108.883        
    num = 0
    for value in XYZ:
        if value > 0.008856:
            value = value ** (0.3333333333333333)
        else:
            value = (7.787 * value) + (16 / 116)
        XYZ[num] = value
        num = num + 1
    Lab = [0, 0, 0]
    L = (116 * XYZ[1]) - 16
    a = 500 * (XYZ[0] - XYZ[1])
    b = 200 * (XYZ[1] - XYZ[2])
    Lab[0] = L
    Lab[1] = a
    Lab[2] = b
    return Lab

def get_color(filepath):
    img = cv2.imread(filepath)
    if img is None:
        return None
    h, w, _ = img.shape
    # sample multiple points or a central region
    # mask out white/black background (e.g. gray > 240 or gray < 30)
    img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    
    # Simple central crop
    ch = h // 2
    cw = w // 2
    roi = img_rgb[ch-50:ch+50, cw-50:cw+50]
    
    # flatten
    pixels = roi.reshape(-1, 3)
    # filter out obvious paper background (too bright or too dark)
    # Actually wait, let's just take median of center. It's usually the paint.
    median_color = np.median(pixels, axis=0)
    
    r, g, b = median_color
    hex_color = '#{:02x}{:02x}{:02x}'.format(int(r), int(g), int(b))
    lab = rgb2lab((r,g,b))
    
    return hex_color, r, g, b, lab[0], lab[1], lab[2]

files = sorted(glob.glob('anh_o/*.png'))
with open('color_results.txt', 'w', encoding='utf-8') as f:
    for file in files:
        res = get_color(file)
        if res:
            hex_c, r, g, b, l, a, b_val = res
            f.write(f"{os.path.basename(file)}: {hex_c}, R:{r:.0f}, G:{g:.0f}, B:{b:.0f}, L:{l:.2f}, a:{a:.2f}, b:{b_val:.2f}\n")
print('Done')
