2d convolution using python and numpy

前端 未结 7 939
鱼传尺愫
鱼传尺愫 2020-12-05 15:48

I am trying to perform a 2d convolution in python using numpy

I have a 2d array as follows with kernel H_r for the rows and H_c for the columns

data          


        
7条回答
  •  盖世英雄少女心
    2020-12-05 16:08

    One of the most obvious is to hard code the kernel.

    img = img.convert('L')
    a = np.array(img)
    out = np.zeros([a.shape[0]-2, a.shape[1]-2], dtype='float')
    out += a[:-2, :-2]
    out += a[1:-1, :-2]
    out += a[2:, :-2]
    out += a[:-2, 1:-1]
    out += a[1:-1,1:-1]
    out += a[2:, 1:-1]
    out += a[:-2, 2:]
    out += a[1:-1, 2:]
    out += a[2:, 2:]
    out /= 9.0
    out = out.astype('uint8')
    img = Image.fromarray(out)
    

    This example does a box blur 3x3 completely unrolled. You can multiply the values where you have a different value and divide them by a different amount. But, if you honestly want the quickest and dirtiest method this is it. I think it beats Guillaume Mougeot's method by a factor of like 5. His method beating the others by a factor of 10.

    It may lose a few steps if you're doing something like a gaussian blur. and need to multiply some stuff.

提交回复
热议问题