test_superresolution.py 9.4 KB
Newer Older
Stephan Seitz's avatar
Stephan Seitz committed
1
2
3
4
5
6
7
8
9
# -*- coding: utf-8 -*-
#
# Copyright © 2019 Stephan Seitz <stephan.seitz@fau.de>
#
# Distributed under terms of the GPLv3 license.

"""

"""
10
11
from os.path import dirname, join

Stephan Seitz's avatar
Stephan Seitz committed
12
import numpy as np
13
import skimage.io
Stephan Seitz's avatar
Stephan Seitz committed
14
import sympy
Stephan Seitz's avatar
Stephan Seitz committed
15
16

import pystencils
17
18
19
20
21
import pystencils_reco.transforms
from pystencils_reco.filters import gauss_filter
from pystencils_reco.resampling import (
    downsample, resample, resample_to_shape, scale_transform, translate)
from pystencils_reco.stencils import BallStencil
Stephan Seitz's avatar
Stephan Seitz committed
22
23
24
25
26
27
28
29
30
31

try:
    import pyconrad.autoinit
except Exception:
    import unittest.mock
    pyconrad = unittest.mock.MagicMock()


def test_superresolution():

32
    x, y = np.random.rand(20, 10), np.zeros((20, 10))
Stephan Seitz's avatar
Stephan Seitz committed
33
34
35
36
37
38
39
40
41
42
43

    kernel = scale_transform(x, y, 0.5).compile()
    print(pystencils.show_code(kernel))
    kernel()

    pyconrad.show_everything()


def test_downsample():
    shape = (20, 10)

44
    x, y = np.random.rand(*shape), np.zeros(tuple(s // 2 for s in shape))
Stephan Seitz's avatar
Stephan Seitz committed
45
46
47
48
49
50

    kernel = downsample(x, y, 2).compile()
    print(pystencils.show_code(kernel))
    kernel()

    pyconrad.show_everything()
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69


def test_warp():
    import torch
    NUM_LENNAS = 5
    perturbation = 0.1

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    warp_vectors = list(perturbation * torch.randn(lenna.shape + (2,)) for _ in range(NUM_LENNAS))

    warped = [torch.zeros(lenna.shape) for _ in range(NUM_LENNAS)]

    warp_kernel = translate(lenna, warped[0], pystencils.autodiff.ArrayWrapper(
        warp_vectors[0], index_dimensions=1), interpolation_mode='linear').compile()

    for i in range(len(warped)):
        warp_kernel(lenna[i], warped[i], warp_vectors[i])
Stephan Seitz's avatar
Stephan Seitz committed
70
71
72
73
74
75
76
77
78
79
80


def test_polar_transform():
    x, y = pystencils.fields('x, y:  float32[2d]')

    x.set_coordinate_origin_to_field_center()
    y.set_coordinate_origin_to_field_center()

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

81
    transformed = np.zeros((400, 400), np.float32)
Stephan Seitz's avatar
Stephan Seitz committed
82
83
84

    resample(x, y).compile()(x=lenna, y=transformed)

85
    pyconrad.show_everything()
86
87
    # while True:
    # sleep(100)
88
89
90
91
92
93
94


def test_polar_transform2():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class PolarTransform(sympy.Function):
        def eval(args):
Stephan Seitz's avatar
Stephan Seitz committed
95
96
97
            return sympy.Matrix((args.norm(),
                                 sympy.atan2(args[1] - x.shape[1] / 2,
                                             args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
98
99
100
101
102
103
104
105
106
107
108
109
110

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = PolarTransform
    y.set_coordinate_origin_to_field_center()

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    transformed = np.zeros((400, 400), np.float32)

    resample(x, y).compile()(x=lenna, y=transformed)

    pyconrad.show_everything()
111
112
    # while True:
    # sleep(100)
113
114
115
116
117
118
119
120


def test_polar_inverted_transform():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class PolarTransform(sympy.Function):
        def eval(args):
            return sympy.Matrix(
121
                (args.norm(), sympy.atan2(args[1] - x.shape[1] / 2, args[0] - x.shape[0] / 2) / sympy.pi * x.shape[1] / 2))
122
123

        def inv():
124
125
            return lambda l: (sympy.Matrix((sympy.cos(l[1] * sympy.pi / x.shape[1] * 2) * l[0],
                                            sympy.sin(l[1] * sympy.pi / x.shape[1] * 2) * l[0]))
Stephan Seitz's avatar
Stephan Seitz committed
126
                              + sympy.Matrix(x.shape) * 0.5)
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = PolarTransform
    y.set_coordinate_origin_to_field_center()
    resample(x, y).compile()(x=lenna, y=transformed)
    resample(y, x).compile()(x=back_transformed, y=transformed)

    pyconrad.show_everything()
143
144
    # while True:
    # sleep(100)
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172


def test_shift():
    x, y = pystencils.fields('x, y:  float32[2d]')

    class ShiftTransform(sympy.Function):
        def eval(args):
            return args + sympy.Matrix((5, 5))

        def inv():
            return lambda l: l - sympy.Matrix((5, 5))

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)

    x.set_coordinate_origin_to_field_center()
    y.coordinate_transform = ShiftTransform
    y.set_coordinate_origin_to_field_center()
    resample(x, y).compile()(x=lenna, y=transformed)
    resample(y, x).compile()(x=back_transformed, y=transformed)

    diff = lenna - back_transformed
    assert diff is not None

    pyconrad.show_everything()
173
174
    # while True:
    # sleep(100)
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218


def test_motion_model():
    x, y = pystencils.fields('x, y:  float32[2d]')
    transform_field = pystencils.fields('t_x, t_y: float32[2d]')

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    back_transformed = np.zeros_like(lenna)
    translate_x = np.zeros((10, 10), np.float32)
    translate_y = np.zeros((10, 10), np.float32)

    pystencils_reco.transforms.extend_to_size_of_other_field(transform_field[0], x)
    pystencils_reco.transforms.extend_to_size_of_other_field(transform_field[1], x)

    shift = sympy.Matrix(sympy.symbols('s:2'))
    shift_val = sympy.Matrix([transform_field[i].interpolated_access(
        transform_field[i].physical_to_index(x.physical_coordinates))
        for i in range(x.ndim)])

    class ShiftTransform(sympy.Function):
        def eval(args):
            return args + shift

        def inv():
            return lambda args: args - shift

    y.coordinate_transform = ShiftTransform
    pystencils_reco.AssignmentCollection([*resample(x, y),
                                          *[pystencils.Assignment(shift[i], shift_val[i]) for i in range(2)]]
                                         ).compile()(x=lenna, y=transformed, t_x=translate_x, t_y=translate_y)

    pystencils_reco.AssignmentCollection([*resample(x, y),
                                          *[pystencils.Assignment(shift[i], shift_val[i]) for i in range(2)]]
                                         ).compile()(x=back_transformed,
                                                     y=transformed,
                                                     t_x=translate_x,
                                                     t_y=translate_y)

    pyconrad.show_everything()
219
220
    # while True:
    # sleep(100)
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252


def test_motion_model2():
    x, y = pystencils.fields('x, y:  float32[2d]')
    transform_field = pystencils.fields('t_x, t_y: float32[2d]')

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    # transformed = np.zeros((400, 400), np.float32)
    # back_transformed = np.zeros((400, 400), np.float32)
    transformed = np.zeros_like(lenna)
    blurred = np.zeros_like(lenna)

    translate_x = np.zeros_like(lenna)
    translate_y = np.zeros_like(lenna)
    amplitude = 20

    resample_to_shape(amplitude * np.random.randn(10, 10).astype(np.float32), lenna.shape).compile()(output=translate_x)
    resample_to_shape(amplitude * np.random.randn(10, 10).astype(np.float32), lenna.shape).compile()(output=translate_y)

    translate(x, y, sympy.Matrix((transform_field[0].center, transform_field[1].center))
              ).compile()(x=lenna, y=transformed, t_x=translate_x, t_y=translate_y)

    # resample(x, y).compile()(x=back_transformed, y=transformed, t_x=translate_x, t_y=translate_y)

    kernel = gauss_filter(transformed, blurred, BallStencil(5, ndim=2), 10).compile()
    print(pystencils.show_code(kernel))
    kernel(input_field=transformed, output_field=blurred)

    pyconrad.show_everything()

253
254
    # while True:
    # sleep(100)
255
256
257
258
259
260
261
262
263
264
265
266
267


def test_spatial_derivative():
    x, y = pystencils.fields('x, y:  float32[2d]')
    tx, ty = pystencils.fields('t_x, t_y: float32[2d]')

    assignments = pystencils.AssignmentCollection({
        y.center: x.interpolated_access((tx.center, 2 * ty.center))
    })

    backward_assignments = pystencils.autodiff.create_backward_assignments(assignments)

    print("backward_assignments: " + str(backward_assignments))
Stephan Seitz's avatar
Stephan Seitz committed
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290


def test_get_shift():
    from pystencils_autodiff.framework_integration.datahandling import PyTorchDataHandling

    lenna_file = join(dirname(__file__), "test_data", "lenna.png")
    lenna = skimage.io.imread(lenna_file, as_gray=True).astype(np.float32)

    dh = PyTorchDataHandling(lenna.shape)
    x, y, tx, ty = dh.add_arrays('x, y, tx, ty')

    dh.cpu_arrays['x'] = lenna
    dh.cpu_arrays['tx'][...] = 0.7
    dh.cpu_arrays['ty'][...] = -0.7
    dh.all_to_gpu()

    kernel = pystencils_reco.AssignmentCollection({
        y.center: x.interpolated_access((tx.center + pystencils.x_, 2 * ty.center + pystencils.y_))
    }).create_pytorch_op()().forward

    dh.run_kernel(kernel)

    pyconrad.imshow(dh.gpu_arrays)