-
Notifications
You must be signed in to change notification settings - Fork 0
/
colorviewer.py
157 lines (123 loc) · 5.73 KB
/
colorviewer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
from __future__ import division
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import colors as mcolors
class ColorViewer(object):
def __init__(self, ax, colormap = None, bin_size = 5, transpose = False, events = [ "press", "hover" ]):
self.ax = ax
if colormap is None:
colormap = mcolors.get_named_colors_mapping()
rgb = dict([ (n, mcolors.to_rgb(c)) for n, c in colormap.iteritems() ])
hsv = dict([ (n, mcolors.rgb_to_hsv(c)) for n, c in rgb.iteritems() ])
colors = [ n for n, c in rgb.iteritems() if all([ v != c[0] for v in c[1:] ]) ]
groups = { }
bins = np.arange(0, 360, bin_size) * (1.0 / 360)
names, hues = zip(*[ (n, h) for n, (h, s, v) in hsv.iteritems() ])
for gr, name in zip(np.digitize(hues, bins), names):
if gr not in groups:
groups[gr] = [ ]
groups[gr].append(name)
self.state = { "selected": None, "background": None }
self.swatches = [ ]
self.rgb_to_swatch, self.label_to_swatch = { }, { }
ordered = lambda c: (c[2], c[1] * -1.0, c[0])
max_y = 0
for x, grp in enumerate(sorted(groups.itervalues(), key = lambda v: hsv[v[0]][0])):
for y, name in enumerate(sorted(grp, key = lambda n: ordered(hsv[n]))):
if transpose:
r = plt.Rectangle((y + 0.1, x + 0.1), 0.8, 0.8, color = rgb[name])
else:
r = plt.Rectangle((x + 0.1, y + 0.1), 0.8, 0.8, color = rgb[name])
ax.add_artist(r)
sw = Swatch(r, name, self.state)
sw.connect(events)
self.swatches.append(sw)
self.rgb_to_swatch[rgb[name]] = sw
self.label_to_swatch[name] = sw
if y > max_y:
max_y = y
if transpose:
ax.set_xlim(0, max_y + 1), ax.set_ylim(0, len(groups))
else:
ax.set_xlim(0, len(groups)), ax.set_ylim(0, max_y + 1)
ax.set_axis_off()
ax.figure.subplots_adjust(left = 0.02, right = 0.98, top = 0.98, bottom = 0.02, hspace = 0, wspace = 0)
self.state["background"] = ax.get_figure().canvas.copy_from_bbox(ax.bbox)
def highlight(self, item):
if isinstance(item, (str, unicode)):
swatch = self.label_to_swatch[item]
elif isinstance(item, tuple):
swatch = self.rgb_to_swatch[item[:3]]
else:
raise Exception("Invalid argument: %s" % str(item))
swatch.select()
if self.state["selected"] is not None:
self.state["selected"].deselect()
self.state["selected"] = swatch
@property
def selected(self):
return tuple(self.state["selected"].rect.get_fc()[:3]) if self.state["selected"] else None
def selected_with_alpha(self, alpha):
return tuple(self.state["selected"].rect.get_fc()[:3], alpha) if self.state["selected"] else None
class Swatch(object):
annotation_props = dict(boxstyle = "square", fc = (0.9, 0.9, 0.9, 1.0), ec = (0.1, 0.1, 0.1, 1.0))
def __init__(self, r, label, state):
self.rect = r
self.label = label
x, y = r.get_xy()
x, y = x + r.get_width() / 2, y + r.get_height() / 2
self.annotation = self.rect.axes.text(x, y, label, bbox = Swatch.annotation_props, visible = False)
self.state = state
def connect(self, events = [ "press", "hover" ]):
if "press" in events:
self.cidpress = self.rect.figure.canvas.mpl_connect('button_press_event', self.on_press)
if "hover" in events:
self.cidmotion = self.rect.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
def select(self):
x, y = self.rect.xy
color = self.rect.get_fc()
ax = self.rect.axes
self.rect.remove()
r = plt.Rectangle((x, y), 0.8, 0.8, fc = color, ec = (0.0, 0.0, 0.0))
ax.add_artist(r)
self.rect = r
def deselect(self):
x, y = self.rect.xy
color = self.rect.get_fc()
ax = self.rect.axes
self.rect.remove()
r = plt.Rectangle((x, y), 0.8, 0.8, color = color)
ax.add_artist(r)
self.rect = r
def on_press(self, event):
if event.inaxes != self.rect.axes:
return
contains, attrd = self.rect.contains(event)
if contains:
self.rect.figure.canvas.restore_region(self.state["background"])
self.annotation.set_visible(False)
if self.state["selected"] is not None:
self.state["selected"].deselect()
self.select()
self.rect.figure.canvas.blit(self.rect.axes)
self.state["selected"] = self
if not contains and self.annotation.get_visible():
self.rect.figure.canvas.restore_region(self.state["background"])
self.annotation.set_visible(False)
self.rect.figure.canvas.blit(self.rect.axes)
self.annotation.figure.canvas.blit(self.rect.axes)
def on_motion(self, event):
if event.inaxes != self.rect.axes:
return
contains, attrd = self.rect.contains(event)
if not contains and self.annotation.get_visible():
self.rect.figure.canvas.restore_region(self.state["background"])
self.annotation.set_visible(False)
self.annotation.figure.canvas.blit(self.rect.axes)
if contains:
self.rect.figure.canvas.restore_region(self.state["background"])
self.annotation.set_visible(True)
self.annotation.figure.canvas.blit(self.rect.axes)
def disconnect(self):
self.rect.figure.canvas.mpl_disconnect(self.cidpress)
self.rect.figure.canvas.mpl_disconnect(self.motion)