cython

Форк
0
/
convolve_py.py 
43 строки · 1.5 Кб
1
import numpy as np
2

3

4
def naive_convolve(f, g):
5
    # f is an image and is indexed by (v, w)
6
    # g is a filter kernel and is indexed by (s, t),
7
    #   it needs odd dimensions
8
    # h is the output image and is indexed by (x, y),
9
    #   it is not cropped
10
    if g.shape[0] % 2 != 1 or g.shape[1] % 2 != 1:
11
        raise ValueError("Only odd dimensions on filter supported")
12
    # smid and tmid are number of pixels between the center pixel
13
    # and the edge, ie for a 5x5 filter they will be 2.
14
    #
15
    # The output size is calculated by adding smid, tmid to each
16
    # side of the dimensions of the input image.
17
    vmax = f.shape[0]
18
    wmax = f.shape[1]
19
    smax = g.shape[0]
20
    tmax = g.shape[1]
21
    smid = smax // 2
22
    tmid = tmax // 2
23
    xmax = vmax + 2 * smid
24
    ymax = wmax + 2 * tmid
25
    # Allocate result image.
26
    h = np.zeros([xmax, ymax], dtype=f.dtype)
27
    # Do convolution
28
    for x in range(xmax):
29
        for y in range(ymax):
30
            # Calculate pixel value for h at (x,y). Sum one component
31
            # for each pixel (s, t) of the filter g.
32
            s_from = max(smid - x, -smid)
33
            s_to = min((xmax - x) - smid, smid + 1)
34
            t_from = max(tmid - y, -tmid)
35
            t_to = min((ymax - y) - tmid, tmid + 1)
36
            value = 0
37
            for s in range(s_from, s_to):
38
                for t in range(t_from, t_to):
39
                    v = x - smid + s
40
                    w = y - tmid + t
41
                    value += g[smid - s, tmid - t] * f[v, w]
42
            h[x, y] = value
43
    return h
44

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.