-
Notifications
You must be signed in to change notification settings - Fork 0
/
patchify.py
48 lines (35 loc) · 1.31 KB
/
patchify.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
# Not mine, found it somewhere in the internet and could not find where. The authors of this, thanks and sorry.
import numpy as np
from skimage.util import view_as_windows
from itertools import product
from typing import Tuple
def patchify(patches, patch_size, step = 1):
return view_as_windows(patches, patch_size, step)
def unpatchify(patches, imsize):
assert len(patches.shape) == 4
i_h, i_w = imsize
image = np.zeros(imsize, dtype=patches.dtype)
divisor = np.zeros(imsize, dtype=patches.dtype)
n_h, n_w, p_h, p_w = patches.shape
# Calculat the overlap size in each axis
if n_h == 1 :
o_h = 0
else:
o_h = (n_h * p_h - i_h) / (n_h - 1)
if n_w ==1 :
o_w = 0
else:
o_w = (n_w * p_w - i_w) / (n_w - 1)
# o_h = (n_h * p_h - i_h) / (n_h - 1)
# The overlap should be integer, otherwise the patches are unable to reconstruct into a image with given shape
assert int(o_w) == o_w
assert int(o_h) == o_h
o_w = int(o_w)
o_h = int(o_h)
s_w = p_w - o_w
s_h = p_h - o_h
for i, j in product(range(n_h), range(n_w)):
patch = patches[i,j]
image[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w] += patch
divisor[(i * s_h):(i * s_h) + p_h, (j * s_w):(j * s_w) + p_w] += 1
return image / divisor