summaryrefslogtreecommitdiff
path: root/silx/math/medianfilter/medianfilter.pyx
blob: c7c9497867a7f813702a8a4b3b28b25be57e093e (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
173
174
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
219
220
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""This module provides median filter function for 1D and 2D arrays.
"""

__authors__ = ["H. Payno", "J. Kieffer"]
__license__ = "MIT"
__date__ = "02/05/2017"


from cython.parallel import prange
cimport cython
cimport median_filter
import numpy
cimport numpy as cnumpy
cdef Py_ssize_t size = 10
from libcpp cimport bool

ctypedef unsigned long uint64
ctypedef unsigned int uint32
ctypedef unsigned short uint16


def medfilt1d(data, kernel_size=3, bool conditional=False):
    """Function computing the median filter of the given input.
    Behavior at boundaries: the algorithm is reducing the size of the
    window/kernel for pixels at boundaries (there is no mirroring).

    :param numpy.ndarray data: the array for which we want to apply
        the median filter. Should be 1d.
    :param kernel_size: the dimension of the kernel.
    :type kernel_size: int
    :param bool conditional: True if we want to apply a conditional median
        filtering.

    :returns: the array with the median value for each pixel.
    """
    return medfilt(data, kernel_size, conditional)


def medfilt2d(image, kernel_size=3, bool conditional=False):
    """Function computing the median filter of the given input.
    Behavior at boundaries: the algorithm is reducing the size of the
    window/kernel for pixels at boundaries (there is no mirroring).

    :param numpy.ndarray data: the array for which we want to apply
        the median filter. Should be 2d.
    :param kernel_size: the dimension of the kernel.
    :type kernel_size: For 1D should be an int for 2D should be a tuple or
        a list of (kernel_height, kernel_width)
    :param bool conditional: True if we want to apply a conditional median
        filtering.

    :returns: the array with the median value for each pixel.
    """
    return medfilt(image, kernel_size, conditional)


def medfilt(data, kernel_size=3, bool conditional=False):
    """Function computing the median filter of the given input.
    Behavior at boundaries: the algorithm is reducing the size of the
    window/kernel for pixels at boundaries (there is no mirroring).

    :param numpy.ndarray data: the array for which we want to apply 
        the median filter. Should be 1d or 2d.
    :param kernel_size: the dimension of the kernel.
    :type kernel_size: For 1D should be an int for 2D should be a tuple or 
        a list of (kernel_height, kernel_width)
    :param bool conditional: True if we want to apply a conditional median
        filtering.

    :returns: the array with the median value for each pixel.
    """
    reshaped = False
    if len(data.shape) == 1:
        data = data.reshape(data.shape[0], 1)
        reshaped = True
    elif len(data.shape) > 2:
        raise ValueError("Invalid data shape. Dimemsion of the arary should be 1 or 2")

    # simple median filter apply into a 2D buffer
    output_buffer = numpy.zeros_like(data)
    check(data, output_buffer)

    if type(kernel_size) in (tuple, list):
        if(len(kernel_size) == 1):
            ker_dim = numpy.array(1, [kernel_size[0]], dtype=numpy.int32)
        else:
            ker_dim = numpy.array(kernel_size, dtype=numpy.int32)
    else:
        ker_dim = numpy.array([kernel_size, kernel_size], dtype=numpy.int32)

    if data.dtype == numpy.float64:
        medfilterfc = _median_filter_float64
    elif data.dtype == numpy.float32:
        medfilterfc = _median_filter_float32
    elif data.dtype == numpy.int64:
        medfilterfc = _median_filter_int64
    elif data.dtype == numpy.uint64:
        medfilterfc = _median_filter_uint64
    elif data.dtype == numpy.int32:
        medfilterfc = _median_filter_int32
    elif data.dtype == numpy.uint32:
        medfilterfc = _median_filter_uint32
    elif data.dtype == numpy.int16:
        medfilterfc = _median_filter_int16
    elif data.dtype == numpy.uint16:
        medfilterfc = _median_filter_uint16
    else:
        raise ValueError("%s type is not managed by the median filter" % data.dtype)

    medfilterfc(input_buffer=data,
                output_buffer=output_buffer,
                kernel_size=ker_dim,
                conditional=conditional)

    if reshaped:
        data = data.reshape(data.shape[0])
        output_buffer = output_buffer.reshape(data.shape[0])

    return output_buffer


def check(input_buffer, output_buffer):
    """Simple check on the two buffers to make sure we can apply the median filter
    """
    if (input_buffer.flags['C_CONTIGUOUS'] is False):
        raise ValueError('<input_buffer> must be a C_CONTIGUOUS numpy array.')

    if (output_buffer.flags['C_CONTIGUOUS'] is False):
        raise ValueError('<output_buffer> must be a C_CONTIGUOUS numpy array.')

    if not (len(input_buffer.shape) <= 2):
        raise ValueError('<input_buffer> dimension must mo higher than 2.')

    if not (len(output_buffer.shape) <= 2):
        raise ValueError('<output_buffer> dimension must mo higher than 2.')

    if not(input_buffer.dtype == output_buffer.dtype):
        raise ValueError('input buffer and output_buffer must be of the same type')

    if not (input_buffer.shape == output_buffer.shape):
        raise ValueError('input buffer and output_buffer must be of the same dimension and same dimension')


######### implementations of the include/median_filter.hpp function ############
@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_float32(float[:, ::1] input_buffer not None,
                           float[:, ::1] output_buffer not None,
                           cnumpy.int32_t[::1] kernel_size not None,
                           bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[float](<float*> & input_buffer[0,0], 
                                               <float*> & output_buffer[0,0], 
                                               <int*>& kernel_size[0],
                                               <int*>buffer_shape,
                                               x,
                                               0,
                                               image_dim,
                                               conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_float64(double[:, ::1] input_buffer not None,
                           double[:, ::1] output_buffer not None,
                           cnumpy.int32_t[::1] kernel_size not None,
                           bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[double](<double*> & input_buffer[0, 0], 
                                                <double*> & output_buffer[0, 0], 
                                                <int*>&kernel_size[0],
                                                <int*>buffer_shape,
                                                x,
                                                0,
                                                image_dim,
                                                conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_int64(cnumpy.int64_t[:, ::1] input_buffer not None,
                         cnumpy.int64_t[:, ::1] output_buffer not None,
                         cnumpy.int32_t[::1] kernel_size not None,
                         bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[long](<long*> & input_buffer[0,0], 
                                              <long*>  & output_buffer[0, 0], 
                                              <int*>&kernel_size[0],
                                                <int*>buffer_shape,
                                                x,
                                                0,
                                                image_dim,
                                                conditional);

@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_uint64(
                          cnumpy.uint64_t[:, ::1] input_buffer not None,
                          cnumpy.uint64_t[:, ::1] output_buffer not None,
                          cnumpy.int32_t[::1] kernel_size not None,
                          bool conditional):

    cdef: 
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[uint64](<uint64*> & input_buffer[0,0], 
                                                <uint64*> & output_buffer[0, 0],
                                                <int*>&kernel_size[0],
                                                <int*>buffer_shape,
                                                x,
                                                0,
                                                image_dim,
                                                conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_int32(cnumpy.int32_t[:, ::1] input_buffer not None,
                         cnumpy.int32_t[:, ::1] output_buffer not None,
                         cnumpy.int32_t[::1] kernel_size not None,
                         bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[int](<int*> & input_buffer[0,0], 
                                             <int*>  & output_buffer[0, 0],
                                             <int*>&kernel_size[0],
                                             <int*>buffer_shape,
                                             x,
                                             0,
                                             image_dim,
                                             conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_uint32(cnumpy.uint32_t[:, ::1] input_buffer not None,
                          cnumpy.uint32_t[:, ::1] output_buffer not None,
                          cnumpy.int32_t[::1] kernel_size not None,
                          bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[uint32](<uint32*> & input_buffer[0,0], 
                                                <uint32*>  & output_buffer[0, 0],
                                                <int*>&kernel_size[0],
                                                <int*>buffer_shape,
                                                x,
                                                0,
                                                image_dim,
                                                conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_int16(cnumpy.int16_t[:, ::1] input_buffer not None,
                         cnumpy.int16_t[:, ::1] output_buffer not None,
                         cnumpy.int32_t[::1] kernel_size not None,
                         bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[short](<short*> & input_buffer[0,0], 
                                               <short*>  & output_buffer[0, 0],
                                               <int*>&kernel_size[0],
                                               <int*>buffer_shape,
                                               x,
                                               0,
                                               image_dim,
                                               conditional)


@cython.cdivision(True)
@cython.boundscheck(False)
@cython.wraparound(False)
@cython.initializedcheck(False)
def _median_filter_uint16(
      cnumpy.ndarray[cnumpy.uint16_t, ndim=2, mode='c'] input_buffer not None,
      cnumpy.ndarray[cnumpy.uint16_t, ndim=2, mode='c'] output_buffer not None,
      cnumpy.ndarray[cnumpy.int32_t, ndim=1, mode='c'] kernel_size not None,
      bool conditional):

    cdef:
        int x = 0
        int image_dim = input_buffer.shape[1] - 1
        int[2] buffer_shape, 
    buffer_shape[0] = input_buffer.shape[0]
    buffer_shape[1] = input_buffer.shape[1]

    for x in prange(input_buffer.shape[0], nogil=True):
            median_filter.median_filter[uint16](<uint16*> & input_buffer[0, 0],
                                                <uint16*> & output_buffer[0, 0],
                                                <int*>&kernel_size[0],
                                                <int*>buffer_shape,
                                                x,
                                                0,
                                                image_dim,
                                                conditional)