forked from amueller/gco_python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.py
83 lines (70 loc) · 2.74 KB
/
example.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
import matplotlib.pyplot as plt
import numpy as np
from pygco import cut_simple, cut_from_graph
def example_binary():
# generate trivial data
x = np.ones((10, 10))
x[:, 5:] = -1
x_noisy = x + np.random.normal(0, 0.8, size=x.shape)
x_thresh = x_noisy > .0
# create unaries
unaries = x_noisy
# as we convert to int, we need to multipy to get sensible values
unaries = (10 * np.dstack([unaries, -unaries]).copy("C")).astype(np.int32)
# create potts pairwise
pairwise = -10 * np.eye(2, dtype=np.int32)
# do simple cut
result = cut_simple(unaries, pairwise)
# use the gerneral graph algorithm
# first, we construct the grid graph
inds = np.arange(x.size).reshape(x.shape)
horz = np.c_[inds[:, :-1].ravel(), inds[:, 1:].ravel()]
vert = np.c_[inds[:-1, :].ravel(), inds[1:, :].ravel()]
edges = np.vstack([horz, vert]).astype(np.int32)
# we flatten the unaries
result_graph = cut_from_graph(edges, unaries.reshape(-1, 2), pairwise)
# plot results
plt.subplot(231, title="original")
plt.imshow(x, interpolation='nearest')
plt.subplot(232, title="noisy version")
plt.imshow(x_noisy, interpolation='nearest')
plt.subplot(233, title="rounded to integers")
plt.imshow(unaries[:, :, 0], interpolation='nearest')
plt.subplot(234, title="thresholding result")
plt.imshow(x_thresh, interpolation='nearest')
plt.subplot(235, title="cut_simple")
plt.imshow(result, interpolation='nearest')
plt.subplot(236, title="cut_from_graph")
plt.imshow(result_graph.reshape(x.shape), interpolation='nearest')
plt.show()
def example_multinomial():
# generate dataset with three stripes
np.random.seed(15)
x = np.zeros((10, 12, 3))
x[:, :4, 0] = -1
x[:, 4:8, 1] = -1
x[:, 8:, 2] = -1
unaries = x + 1.5 * np.random.normal(size=x.shape)
x = np.argmin(x, axis=2)
unaries = (unaries * 10).astype(np.int32)
x_thresh = np.argmin(unaries, axis=2)
# potts potential
pairwise_potts = -2 * np.eye(3, dtype=np.int32)
result = cut_simple(unaries, 10 * pairwise_potts)
# potential that penalizes 0-1 and 1-2 less thann 0-2
pairwise_1d = -15 * np.eye(3, dtype=np.int32) - 8
pairwise_1d[-1, 0] = 0
pairwise_1d[0, -1] = 0
print(pairwise_1d)
result_1d = cut_simple(unaries, pairwise_1d)
plt.subplot(141, title="original")
plt.imshow(x, interpolation="nearest")
plt.subplot(142, title="thresholded unaries")
plt.imshow(x_thresh, interpolation="nearest")
plt.subplot(143, title="potts potentials")
plt.imshow(result, interpolation="nearest")
plt.subplot(144, title="1d topology potentials")
plt.imshow(result_1d, interpolation="nearest")
plt.show()
example_binary()
example_multinomial()