-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharray_utils.py
More file actions
66 lines (58 loc) · 2.87 KB
/
Copy patharray_utils.py
File metadata and controls
66 lines (58 loc) · 2.87 KB
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
import numpy as np
def collage_reshape(x, pad_width=0, pad_value=0):
"""
Parameters
----------
x : (H, W, h, w ...) np.ndarray
pad_width : non-negative int
Returns
-------
x_reshaped : (H * h, W * w ...) np.ndarray
Examples
--------
>>> x = [ [np.full((2, 4, 1), i * 3 + j + 1) for j in xrange(3)] for i in xrange(5) ]
>>> np.asarray(x).shape # 5x3 grid of 2x4x1 "images" with constant digits
(5, 3, 2, 4, 1)
>>> z = collage_reshape(x)
>>> z.shape
(10, 12, 1)
>>> z[..., -1]
array([[ 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
[ 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
[ 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
[ 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6],
[ 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9],
[ 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9],
[10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12],
[10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12],
[13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15],
[13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15]])
>>> collage_reshape(x, pad_width=1)[..., -1]
array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 1, 1, 1, 1, 0, 2, 2, 2, 2, 0, 3, 3, 3, 3, 0],
[ 0, 1, 1, 1, 1, 0, 2, 2, 2, 2, 0, 3, 3, 3, 3, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 4, 4, 4, 4, 0, 5, 5, 5, 5, 0, 6, 6, 6, 6, 0],
[ 0, 4, 4, 4, 4, 0, 5, 5, 5, 5, 0, 6, 6, 6, 6, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 7, 7, 7, 7, 0, 8, 8, 8, 8, 0, 9, 9, 9, 9, 0],
[ 0, 7, 7, 7, 7, 0, 8, 8, 8, 8, 0, 9, 9, 9, 9, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 10, 10, 10, 10, 0, 11, 11, 11, 11, 0, 12, 12, 12, 12, 0],
[ 0, 10, 10, 10, 10, 0, 11, 11, 11, 11, 0, 12, 12, 12, 12, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 13, 13, 13, 13, 0, 14, 14, 14, 14, 0, 15, 15, 15, 15, 0],
[ 0, 13, 13, 13, 13, 0, 14, 14, 14, 14, 0, 15, 15, 15, 15, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
"""
x = np.asarray(x)
assert x.ndim >= 4
if pad_width:
pw = [(0, 0), (0, 0), (0, pad_width), (0, pad_width)] + [(0, 0)] * (x.ndim - 4)
x = np.pad(x, pw, mode='constant', constant_values=pad_value)
H, W, h, w = x.shape[:4]
x = x.swapaxes(1, 2).reshape(H * h, W * w, *x.shape[4:])
if pad_width:
pw = [(pad_width, 0), (pad_width, 0)] + [(0, 0)] * (x.ndim - 2)
x = np.pad(x, pw, mode='constant', constant_values=pad_value)
return x