使用python和numpy进行2D卷积 [英] 2d convolution using python and numpy

查看:445
本文介绍了使用python和numpy进行2D卷积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用numpy在python中执行2d卷积

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

我有一个二维数组,其中行H_r,列H_c

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

data = np.zeros((nr, nc), dtype=np.float32)

#fill array with some data here then convolve

for r in range(nr):
    data[r,:] = np.convolve(data[r,:], H_r, 'same')

for c in range(nc):
    data[:,c] = np.convolve(data[:,c], H_c, 'same')

data = data.astype(np.uint8);

它不会产生我期望的输出,此代码看起来还不错,我认为问题出在从float32到8bit的转换上.最好的方法是什么

It does not produce the output that I was expecting, does this code look OK, I think the problem is with the casting from float32 to 8bit. Whats the best way to do this

谢谢

推荐答案

也许它不是最优化的解决方案,但这是我之前在python的numpy库中使用的实现:

Maybe it is not the most optimized solution, but this is an implementation I used before with numpy library for Python:

def convolution2d(image, kernel, bias):
    m, n = kernel.shape
    if (m == n):
        y, x = image.shape
        y = y - m + 1
        x = x - m + 1
        new_image = np.zeros((y,x))
        for i in range(y):
            for j in range(x):
                new_image[i][j] = np.sum(image[i:i+m, j:j+m]*kernel) + bias
return new_image

我希望这段代码可以帮助其他有同样疑问的人.

I hope this code helps other guys with the same doubt.

致谢.

这篇关于使用python和numpy进行2D卷积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆