-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
mm_color_select.py
88 lines (62 loc) · 2.21 KB
/
mm_color_select.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
# Based on a blog post by Steve Eddins:
# http://blogs.mathworks.com/steve/2010/12/23/two-dimensional-histograms/
from skimage import io, color, exposure
import numpy as np
url = 'http://blogs.mathworks.com/images/steve/2010/mms.jpg'
import os
if not os.path.exists('mm.jpg'):
print("Downloading M&M's...")
from urllib.request import urlretrieve
urlretrieve(url, 'mm.jpg')
mm = io.imread('mm.jpg')
mm_lab = color.rgb2lab(mm)
L, a, b = mm_lab.T
left, right = -100, 100
bins = np.arange(left, right)
H, x_edges, y_edges = np.histogram2d(a.flatten(), b.flatten(), bins,
normed=True)
import matplotlib.pyplot as plt
from matplotlib.widgets import RectangleSelector
from matplotlib.patches import Rectangle
f = plt.figure()
ax0 = plt.subplot2grid((2, 2), (0, 0))
ax1 = plt.subplot2grid((2, 2), (0, 1), rowspan=2)
ax2 = plt.subplot2grid((2, 2), (1, 0))
f.suptitle('Select values by dragging the mouse on the histogram')
ax0.imshow(mm)
ax0.set_title('Input')
ax0.set_xticks([])
ax0.set_yticks([])
ax1.imshow(exposure.rescale_intensity(H, in_range=(0, 5e-4)),
extent=[left, right, right, left], cmap=plt.cm.gray)
ax1.set_title('Histogram')
ax1.set_xlabel('b')
ax1.set_ylabel('a')
rectprops=dict(
facecolor='gray',
edgecolor='white',
alpha=0.3
)
selected_rectangle = Rectangle((0, 0), 0, 0, transform=ax1.transData,
**rectprops)
ax1.add_patch(selected_rectangle)
result = ax2.imshow(mm)
ax2.set_title('L + masked a, b')
def histogram_select(e_click, e_release):
x0, y0 = e_click.xdata, e_click.ydata
x1, y1 = e_release.xdata, e_release.ydata
x0, x1 = min(x0, x1), max(x0, x1)
y0, y1 = min(y0, y1), max(y0, y1)
selected_rectangle.set_xy((x0, y0))
selected_rectangle.set_height(y1 - y0)
selected_rectangle.set_width(x1 - x0)
green_mm_lab = mm_lab.copy()
L, a, b = green_mm_lab.T
mask = ((a > y0) & (a < y1)) & ((b > x0) & (b < x1))
green_mm_lab[..., 1:][~mask.T] = 0
green_mm = color.lab2rgb(green_mm_lab)
result.set_data(green_mm)
f.canvas.draw()
rs = RectangleSelector(ax1, histogram_select, drawtype='box',
spancoords='data', rectprops=rectprops)
plt.show()