Skip to content

Instantly share code, notes, and snippets.

@monkut
Created February 17, 2015 05:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkut/d0c03a06e89de037839c to your computer and use it in GitHub Desktop.
Save monkut/d0c03a06e89de037839c to your computer and use it in GitHub Desktop.
Used this script to minimalize osm-bright mml colors to grayscale for creating a data base layer map in tilemill.
"""
Script to replace color #RRGGBB formated values to grayscale values inplace.
usage:
python hexcolor2grayscale.py filename1 filename2
"""
import fileinput
import sys
import re
import colorsys
def color2grayscale(values):
rgb = None
if values:
# process as hex (ignore alpha)
# values 0-255
if len(values) == 3:
# (3 digit) patterns are converted by doubling each hex digit
# --> #abc is equivalent to #aabbcc
rgb = [int(v+v, 16)/255 for v in values]
elif len(values) == 6:
rgb = [int(values[i:i+2], 16)/255 for i in range(0, 6, 2)]
result = values
if rgb:
luma, i, q = colorsys.rgb_to_yiq(*rgb)
# get just the luma channel, convert back to rgb
gray_rgb = colorsys.yiq_to_rgb(luma, 0, 0)
result = "#{}".format("".join("{:02X}".format(int(v * 255)) for v in gray_rgb))
return result
_hex_colour = re.compile(r'#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})\b')
def replace(match):
value = match.group(1)
if value:
result = color2grayscale(value)
else:
result = value
return result
for line in fileinput.input(inplace=True):
line = _hex_colour.sub(replace, line)
sys.stdout.write(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment