Skip to content

Instantly share code, notes, and snippets.

@dyf
Created January 3, 2017 17:43
Show Gist options
  • Save dyf/51b25bddfc3338c5cdf3311402dc3610 to your computer and use it in GitHub Desktop.
Save dyf/51b25bddfc3338c5cdf3311402dc3610 to your computer and use it in GitHub Desktop.
convert the color_hex_triplet values in mouse connectivity's structures.csv to 8-bit RGB values
import csv
def hex_str_to_rgb(hex_str):
""" convert a hex string (e.g. "FFFFFF") to an RGB dictionary """
val = int(hex_str, 16)
return {
'r': val & 0x0000ff,
'g': (val & 0x00ff00) >> 8,
'b': val >> 16
}
input_csv = 'mcc/structures.csv'
output_csv = 'structures_rgb.csv'
# read structures.csv as a list of dictionaries
with open(input_csv,'rb') as f:
reader = csv.DictReader(f)
structures = list(reader)
# add the r/g/b extra columns to the list of structures
for structure in structures:
# convert the hex string to an integer
rgb = hex_str_to_rgb(structure['color_hex_triplet'])
structure['rgb_r'] = rgb['r']
structure['rgb_g'] = rgb['g']
structure['rgb_b'] = rgb['b']
# write updated structures to a new file
with open(output_csv,'wb') as f:
writer = csv.DictWriter(f, fieldnames=sorted(structures[0].keys()))
writer.writeheader()
for structure in structures:
writer.writerow(structure)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment