Created
          July 16, 2025 00:10 
        
      - 
      
 - 
        
Save jdloft/fb14c7ea6d856ec793b5e65139996be1 to your computer and use it in GitHub Desktop.  
    Find closest color in xterm-256color to solarized colors
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import yaml | |
| from colormath.color_objects import sRGBColor, LabColor | |
| from colormath.color_conversions import convert_color | |
| from colormath.color_diff import delta_e_cie2000 | |
| import numpy | |
| def patch_asscalar(a): | |
| return a.item() | |
| setattr(numpy, "asscalar", patch_asscalar) | |
| def load_xterm_palette(yaml_path): | |
| with open(yaml_path, 'r') as f: | |
| data = yaml.safe_load(f) | |
| palette = [] | |
| for section in (':xterm16', ':xtermGreyscale', ':xterm256'): | |
| for idx_str, hex_code in data.get(section, []): | |
| palette.append((int(idx_str), hex_code.lower())) | |
| return palette | |
| def closest_xterm_index(target_hex, palette): | |
| target_rgb = sRGBColor.new_from_rgb_hex(target_hex) | |
| target_lab = convert_color(target_rgb, LabColor) | |
| min_dist = float('inf') | |
| best_match = None | |
| for index, hex_code in palette: | |
| rgb = sRGBColor.new_from_rgb_hex(hex_code) | |
| lab = convert_color(rgb, LabColor) | |
| dist = delta_e_cie2000(target_lab, lab) | |
| if dist < min_dist: | |
| min_dist = dist | |
| best_match = (index, hex_code) | |
| return best_match | |
| palette = load_xterm_palette("xterm-256color.yaml") | |
| base03="#002b36" | |
| base02="#073642" | |
| base01="#586e75" | |
| base00="#657b83" | |
| base0="#839496" | |
| base1="#93a1a1" | |
| base2="#eee8d5" | |
| base3="#fdf6e3" | |
| yellow="#b58900" | |
| orange="#cb4b16" | |
| red="#dc322f" | |
| magenta="#d33682" | |
| violet="#6c71c4" | |
| blue="#268bd2" | |
| cyan="#2aa198" | |
| green="#859900" | |
| # matches_to_find = [base01, base00, base0, violet, base1, base03] | |
| matches_to_find = [base01, base02, base00, base0, base1, violet] | |
| for color in matches_to_find: | |
| match = closest_xterm_index(color, palette) | |
| print(match) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment