Skip to content

Commit d2f618b

Browse files
committed
Added problem set - 5's p1 and p2
1 parent 870f668 commit d2f618b

File tree

76 files changed

+164
-6
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

76 files changed

+164
-6
lines changed

ps_2/ps2.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,8 @@ def test_disparity_on_noise(disparity_compute, noise_type, object_name_prefix='p
5454
imread_from_rep('pair1-D_L', grey_scale=True),
5555
imread_from_rep('pair1-D_R', grey_scale=True)],
5656
['left', 'right', 'd_l', 'd_r', 'd_l noise', 'd_r noise', 'ground truth l', 'ground truth l'], shape=(4, 2))
57-
imsave(d_l_noise, 'output/ ps2-3-a-1.png')
58-
imsave(d_r_noise, 'output/ ps2-3-a-2.png')
57+
imsave(d_l_noise, 'output/ps2-3-a-1.png')
58+
imsave(d_r_noise, 'output/ps2-3-a-2.png')
5959

6060

6161
def p3():

ps_4/helper.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,9 @@
66
from scipy.spatial import ConvexHull
77

88

9-
def im_der(im, with_norm=False):
9+
def im_der(im):
1010
gx = cv.Sobel(im, cv.CV_64F, 1, 0, ksize=3)
1111
gy = cv.Sobel(im, cv.CV_64F, 0, 1, ksize=3)
12-
if not with_norm:
13-
return gx, gy
1412
return gx, gy,
1513

1614

ps_5/helper.py

+91
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
import numpy as np
2+
import cv2 as cv
3+
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
4+
import matplotlib.pyplot as plt
5+
6+
7+
def get_pixel_derivatives(im_t0, im_t1):
8+
t0, t1 = im_t0.astype(np.float32), im_t1.astype(np.float32)
9+
ix, iy = np.zeros(t0.shape, dtype=np.float32), np.zeros(t0.shape, dtype=np.float32)
10+
ix[1:-1, 1:-1, ...] = t0[1:-1, 2:, ...] - t0[1:-1, :-2, ...]
11+
iy[1:-1, 1:-1, ...] = t0[2:, 1:-1, ...] - t0[:-2, 1:-1, ...]
12+
return ix, iy, (t0 - t1).astype(np.float32)
13+
14+
15+
def lucas_kanade(im0, im1, k_shape=(5, 5)):
16+
ix, iy, it = get_pixel_derivatives(im0, im1)
17+
grad_prods = [ix * ix, ix * iy, iy * iy, ix * it, iy * it]
18+
grad_prods = [np.sum(grad_prod, axis=2) for grad_prod in grad_prods] if len(im0.shape) == 3 else grad_prods
19+
wgps = [cv.GaussianBlur(grad_prod, k_shape, 0) for grad_prod in grad_prods]
20+
wgps = np.concatenate([wgp[:, :, np.newaxis] for wgp in wgps], axis=2)
21+
m_flow = np.zeros(im0.shape[:2] + (2,), dtype=np.float32)
22+
(w_h, w_l) = map(lambda x: (x - 1) // 2, k_shape)
23+
for i in range(w_h, im0.shape[0] - w_h):
24+
for j in range(w_l, im0.shape[1] - w_l):
25+
a = [[wgps[i, j, 0], wgps[i, j, 1]], [wgps[i, j, 1], wgps[i, j, 2]]]
26+
b = [[-wgps[i, j, 3]], [-wgps[i, j, 4]]]
27+
uv, _, rank, _ = np.linalg.lstsq(a, b, rcond=0.1)
28+
m_flow[i, j, 0] = uv[0] if rank == 2 else 0
29+
m_flow[i, j, 1] = uv[1] if rank == 2 else 0
30+
return -m_flow
31+
32+
33+
def get_flow_arrows(flow, gap=None, show_arrows_on_plt=False):
34+
gap = [gap, flow.shape[0] // 30][gap is None]
35+
x = np.arange(0, flow.shape[1], 1)
36+
y = np.arange(0, flow.shape[0], 1)
37+
x, y = np.meshgrid(x, y)
38+
fig = plt.figure()
39+
axs = fig.add_axes([0, 0, 1, 1], frameon=False)
40+
fig.patch.set_alpha(0)
41+
axs.patch.set_alpha(0)
42+
canvas = FigureCanvas(fig)
43+
plt.quiver(x[::gap, ::gap], y[::-gap, ::-gap], flow[::gap, ::gap, 0], -flow[::gap, ::gap, 1], color='red')
44+
axs.axis('off')
45+
axs.margins(0)
46+
canvas.draw()
47+
image_from_plot = np.frombuffer(fig.canvas.tostring_argb(), dtype=np.uint8)
48+
image_from_plot = image_from_plot.reshape(fig.canvas.get_width_height()[::-1] + (4,))
49+
if not show_arrows_on_plt:
50+
plt.close(fig)
51+
return cv.resize(image_from_plot, dsize=flow.shape[1::-1])
52+
53+
54+
def add_flow_over_im(im, flow, show_arrows_on_plt=False):
55+
im = im.copy()
56+
if len(im.shape) == 2:
57+
im = cv.cvtColor(im, cv.COLOR_GRAY2RGB)
58+
arrows_arbg = get_flow_arrows(flow, show_arrows_on_plt=show_arrows_on_plt)
59+
alpha = arrows_arbg[:, :, 0]
60+
for i in range(3):
61+
im[:, :, i] = (alpha / 255.0) * arrows_arbg[:, :, 1 + i] + ((255.0 - alpha) / 255.0) * im[:, :, i]
62+
return im
63+
64+
65+
def reduce(im):
66+
im_blur = cv.GaussianBlur(im, (5, 5), 0)
67+
return im_blur[::2, ::2, ...]
68+
69+
70+
def expand(im, dst_size):
71+
return cv.GaussianBlur(cv.resize(im, dst_size[1::-1], interpolation=cv.INTER_NEAREST), (5, 5), 0)
72+
73+
74+
def gaussian_pyramid(im, max_l=np.PINF):
75+
levels = min(int(np.log2(min(im.shape[:2])) + 1), max_l)
76+
g_pyr = [im]
77+
[g_pyr.append(reduce(g_pyr[-1])) for i in range(levels-1)]
78+
return g_pyr
79+
80+
81+
def laplacian_pyramid(im, max_l=np.PINF):
82+
levels = min(int(np.log2(min(im.shape[:2])) + 1), max_l)
83+
l_pyr = [im]
84+
for i in range(levels - 1):
85+
tmp = reduce(l_pyr[-1])
86+
l_pyr[-1] = l_pyr[-1].astype(np.int32) - expand(tmp, l_pyr[-1].shape).astype(np.int32)
87+
l_pyr.append(tmp)
88+
return l_pyr
89+
90+
91+

ps_5/input/DataSeq1/yos_img_01.jpg

64.3 KB

ps_5/input/DataSeq1/yos_img_02.jpg

64.4 KB

ps_5/input/DataSeq1/yos_img_03.jpg

64.2 KB

ps_5/input/DataSeq2/0.png

374 KB

ps_5/input/DataSeq2/1.png

373 KB

ps_5/input/DataSeq2/2.png

372 KB

ps_5/input/Juggle/0.png

325 KB

ps_5/input/Juggle/1.png

326 KB

ps_5/input/Juggle/2.png

326 KB

ps_5/input/TestSeq/Shift0.png

33.7 KB

ps_5/input/TestSeq/ShiftR10.png

33.6 KB

ps_5/input/TestSeq/ShiftR2.png

33.6 KB

ps_5/input/TestSeq/ShiftR20.png

33.5 KB

ps_5/input/TestSeq/ShiftR40.png

33.6 KB

ps_5/input/TestSeq/ShiftR5U5.png

33.6 KB
Binary file not shown.

ps_5/observations/AFigure(s).png

456 KB

ps_5/observations/AFigure1(s).png

454 KB

ps_5/observations/Figure(s).png

374 KB

ps_5/observations/Figure1(s).png

374 KB

ps_5/output/ps5-1-a-1.png

115 KB

ps_5/output/ps5-1-a-2.png

125 KB

ps_5/output/ps5-1-b-1.png

122 KB

ps_5/output/ps5-1-b-2.png

123 KB

ps_5/output/ps5-1-b-3.png

124 KB

ps_5/output/ps5-2-a-1.png

131 KB

ps_5/output/ps5-2-a-2.png

32.3 KB

ps_5/output/ps5-2-a-3.png

8.38 KB

ps_5/output/ps5-2-a-4.png

2.31 KB

ps_5/output/ps5-2-b-1.png

131 KB

ps_5/output/ps5-2-b-2.png

32.3 KB

ps_5/output/ps5-2-b-3.png

8.38 KB

ps_5/output/ps5-2-b-4.png

2.31 KB

ps_5/ps5.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import numpy as np
2+
from ps_5.helper import lucas_kanade, add_flow_over_im, reduce, gaussian_pyramid, expand, laplacian_pyramid
3+
from ps_hepers.helpers import imread_from_rep, imshow, np_load, imsave, np_save, imfix_scale
4+
5+
6+
def p1_a():
7+
a = imread_from_rep('TestSeq/Shift0', grey_scale=True)
8+
b = imread_from_rep('TestSeq/ShiftR2', grey_scale=True)
9+
c = imread_from_rep('TestSeq/ShiftR5U5', grey_scale=True)
10+
d = imread_from_rep('TestSeq/ShiftR10', grey_scale=True)
11+
e = imread_from_rep('TestSeq/ShiftR20', grey_scale=True)
12+
f = imread_from_rep('TestSeq/ShiftR40', grey_scale=True)
13+
14+
#a
15+
flow1 = lucas_kanade(a, b, (15, 15))
16+
a_flow1 = add_flow_over_im(a, flow1)
17+
flow2 = lucas_kanade(a, c, (47, 47))
18+
a_flow2 = add_flow_over_im(a, flow2)
19+
imsave(a_flow1, 'output/ps5-1-a-1.png')
20+
imsave(a_flow2, 'output/ps5-1-a-2.png')
21+
imshow([a_flow1, a_flow2], ['right shift', 'top right shift'], cmap='gray')
22+
23+
#b
24+
flow_ims = [add_flow_over_im(a, lucas_kanade(a, x, (47, 47))) for x in [d, e, f]]
25+
imshow(flow_ims,['r10', 'r20', 'r40'], shape=(3,1))
26+
[imsave(im, 'output/ps5-1-b-%s.png' % (i+1)) for i, im in zip(range(len(flow_ims)), flow_ims)]
27+
28+
29+
def p1_exp():
30+
im_names = ['TestSeq/Shift0', 'TestSeq/ShiftR5U5']
31+
w_start = 5
32+
w_end = 81
33+
window_range = np.arange(w_start, w_end, 2)
34+
exp_name = ','.join([i.replace('/', '-') for i in im_names])
35+
w_range_as_str = 'w%s-%s' % (w_start, w_end)
36+
a = imread_from_rep(im_names[0], grey_scale=True)
37+
b = imread_from_rep(im_names[1], grey_scale=True)
38+
flow_window_list = np_load(len(window_range), 'objects/flow_%s_%s.npy' % (w_range_as_str, exp_name))
39+
if flow_window_list is None or len(flow_window_list) != len(window_range):
40+
flow_window_list = []
41+
for w in window_range:
42+
print('processing images for motion flow with window size %s' % w)
43+
flow1 = add_flow_over_im(a, lucas_kanade(a, b, (w, w)))
44+
flow_window_list.append((w, flow1))
45+
imsave(flow1, 'observations/flow_%s_w_size_%s.png' % (exp_name, w))
46+
np_save(np.asarray(flow_window_list, dtype=object), 'objects/flow_%s_%s.npy' % (w_range_as_str, exp_name))
47+
48+
def update_exp(x, axs, sliders, buttons):
49+
i = np.abs(window_range - sliders[0].val).argmin()
50+
return [0], [flow_window_list[i][1]]
51+
52+
slider_attr = [{'label': 'Window Size', 'valmin': w_start, 'valmax': w_end, 'valstep': 2}]
53+
imshow(flow_window_list[0][1], [' Detected Optical Flow'], slider_attr=slider_attr, slider_callback=[update_exp])
54+
55+
56+
def p2():
57+
im = imread_from_rep('DataSeq1/yos_img_01', extension='.jpg')
58+
g_py = gaussian_pyramid(im, 4)
59+
imshow(g_py)
60+
[imsave(g_py[i], 'output/ps5-2-a-%s.png' % (i+1)) for i in range(len(g_py))]
61+
l_py = laplacian_pyramid(im, 4)
62+
imshow([imfix_scale(i) for i in l_py])
63+
[imsave(g_py[i], 'output/ps5-2-b-%s.png' % (i+1)) for i in range(len(g_py))]
64+
65+
66+
if __name__ == '__main__':
67+
# p1_a()
68+
# p1_exp()
69+
p2()

ps_hepers/helpers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def imshow(im, im_title=None, shape=None, interpolation='bilinear', cmap=None, s
116116
axs[i].imshow(im[i], interpolation=interpolation, cmap=cmap)
117117
else:
118118
axs[i].imshow(im[i], interpolation=interpolation)
119-
axs_title = '%s $%sx%s$ $mn=%s$ $mx=%s$ ' % (
119+
axs_title = '%s $%sx%s$\n$mn=%.3f$ $mx=%.3f$ ' % (
120120
im_title if not type(im_title) == list else im_title[i], im[i].shape[0], im[i].shape[1], np.min(im[i]),
121121
np.max(im[i]))
122122
axs[i].set_title(axs_title, fontweight='bold')

0 commit comments

Comments
 (0)