-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathex1_utils.py
80 lines (59 loc) · 2.77 KB
/
ex1_utils.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
import math
import numpy as np
import cv2
from matplotlib.colors import hsv_to_rgb
def gaussderiv(img, sigma):
x = np.array(list(range(math.floor(-3.0 * sigma + 0.5), math.floor(3.0 * sigma + 0.5) + 1)))
G = np.exp(-x ** 2 / (2 * sigma ** 2))
G = G / np.sum(G)
D = -2 * (x * np.exp(-x ** 2 / (2 * sigma ** 2))) / (np.sqrt(2 * math.pi) * sigma ** 3)
D = D / (np.sum(np.abs(D)) / 2)
Dx = cv2.sepFilter2D(img, -1, D, G)
Dy = cv2.sepFilter2D(img, -1, G, D)
return Dx, Dy
def gausssmooth(img, sigma):
x = np.array(list(range(math.floor(-3.0 * sigma + 0.5), math.floor(3.0 * sigma + 0.5) + 1)))
G = np.exp(-x ** 2 / (2 * sigma ** 2))
G = G / np.sum(G)
return cv2.sepFilter2D(img, -1, G, G)
def show_flow(U, V, ax, type='field', set_aspect=False):
if type == 'field':
scaling = 0.1
u = cv2.resize(gausssmooth(U, 1.5), (0, 0), fx=scaling, fy=scaling)
v = cv2.resize(gausssmooth(V, 1.5), (0, 0), fx=scaling, fy=scaling)
x_ = (np.array(list(range(1, u.shape[1] + 1))) - 0.5) / scaling
y_ = -(np.array(list(range(1, u.shape[0] + 1))) - 0.5) / scaling
x, y = np.meshgrid(x_, y_)
ax.quiver(x, y, -u * 5, v * 5)
if set_aspect:
ax.set_aspect(1.)
elif type == 'magnitude':
magnitude = np.sqrt(U ** 2 + V ** 2)
ax.imshow(np.minimum(1, magnitude))
elif type == 'angle':
angle = np.arctan2(V, U) + math.pi
im_hsv = np.concatenate((np.expand_dims(angle / (2 * math.pi), -1),
np.expand_dims(np.ones(angle.shape, dtype=np.float32), -1),
np.expand_dims(np.ones(angle.shape, dtype=np.float32), -1)), axis=-1)
ax.imshow(hsv_to_rgb(im_hsv))
elif type == 'angle_magnitude':
magnitude = np.sqrt(U ** 2 + V ** 2)
angle = np.arctan2(V, U) + math.pi
im_hsv = np.concatenate((np.expand_dims(angle / (2 * math.pi), -1),
np.expand_dims(np.minimum(1, magnitude), -1),
np.expand_dims(np.ones(angle.shape, dtype=np.float32), -1)), axis=-1)
ax.imshow(hsv_to_rgb(im_hsv))
else:
print(f'Error: unknown optical flow visualization type: {type}.')
exit(-1)
def rotate_image(img, angle):
center = tuple(np.array(img.shape[1::-1]) / 2)
rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
rotated = cv2.warpAffine(img, rot_mat, img.shape[1::-1], flags=cv2.INTER_LINEAR)
return rotated
def calculate_derivatives(img1, img2, smoothing, derivation):
i_t = gausssmooth(img2 - img1, smoothing)
i_x, i_y = gaussderiv(gausssmooth(np.divide(img1 + img2, 2), smoothing), derivation)
return i_x, i_y, i_t
def sum_kernel(x, N):
return cv2.filter2D(x, -1, np.ones((N, N)))