Skip to content

Instantly share code, notes, and snippets.

@rosskarchner
Created December 14, 2016 18:26
Show Gist options
  • Save rosskarchner/2464eda2032d1f98a48c8d66136a5db1 to your computer and use it in GitHub Desktop.
Save rosskarchner/2464eda2032d1f98a48c8d66136a5db1 to your computer and use it in GitHub Desktop.
I wrote this a few years ago when I was playing around with color math-- I'm not sure I could explain it all at this point, but I made some tweaks that let it work with the latest version of colormath.
import svgwrite
import random
from colormath.color_objects import sRGBColor, HSVColor
from colormath.color_conversions import convert_color
from collections import deque
from copy import copy
BOARD_WIDTH = "24in"
BOARD_HEIGHT = "12in"
BOARD_SIZE = (BOARD_WIDTH, BOARD_HEIGHT)
WHITE = sRGBColor(1,1,1)
BLACK = sRGBColor(0,0,0)
r = lambda: random.randint(0, 255)
def color_for_hex(hexcode):
color = sRGBColor.new_from_rgb_hex(hexcode)
return color
def random_color():
hexcode = ('#%02X%02X%02X' % (r(), r(), r()))
print hexcode
return color_for_hex(hexcode)
def color_distance(first,second):
return first.delta_e(second)
def random_ish_color(previous_color=None):
rc = random_color()
if not previous_color:
return rc
while (color_distance(rc, previous_color) < 10 and rc.delta_e(BLACK) < 50):
rc = random_color()
return rc
def triads(color):
color_as_hex = color.get_rgb_hex()
rgb = deque([color_as_hex[1:3], color_as_hex[3:5], color_as_hex[5:7]])
rgb.rotate()
triad1 = color_for_hex('#' + ''.join(copy(rgb)))
rgb.rotate()
triad2 = color_for_hex('#' + ''.join(copy(rgb)))
return (triad1, triad2)
def HueShift(h, s):
h += s
while (h >= 360.0):
h -= 360.0
while (h < 0.0):
h += 360.0
return h
def complement(rgb):
hsv = convert_color(rgb, HSVColor)
new_h = HueShift(hsv.hsv_h, 180)
hsv.hsv_h = new_h
new_rgb = hsv.convert_to('rgb')
return new_rgb
def draw_board(dwg):
for y in range(12):
starting_color = random_color()
hsv = convert_color(starting_color, HSVColor)
for x in range(24):
saturation = random.random()
value = random.random()
hsv.hsv_s = saturation
hsv.hsv_v =value
as_rgb = convert_color(hsv, sRGBColor)
square = dwg.rect(insert=(x, y),
size=(1, 1),
fill=as_rgb.get_rgb_hex())
dwg.add(square)
def main():
dwg = svgwrite.Drawing('banner.svg', size=BOARD_SIZE)
dwg.viewbox(0, 0, 24, 12)
# set background
dwg.add(dwg.rect(size=('100%', '100%'), fill="white"))
draw_board(dwg)
dwg.save()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment