【问题标题】:Convolving an image with kernel returns empty image将图像与内核卷积会返回空图像
【发布时间】:2021-09-09 18:44:14
【问题描述】:

我接受了一个挑战,用 Python 自己实现了一些 OpenCV 函数。很多这些函数都需要将图像与内核进行卷积,所以这是我编写的函数:

def convolve(img, kernel):  # img should have zero padding 
    kx, ky = kernel.shape  # kernel is square so kx == ky
    start, end = floor(kx / 2), ceil(kx / 2)
    x, y = img.shape
    convolved = np.zeros((x, y))

    for i in range(kx, x - kx):
        for j in range(kx, y - kx):
            convolved_area = img[i - start:i + end, j - start:j + end] * kernel
            convolved[i][j] = np.sum(convolved_area)

    return convolved

当我在一个图像和一个我制作的内核上运行它时,我收到一个白色图像,唯一的颜色是黑色填充。

为了测试,我使用的内核是高斯内核:

for x in range(radius):
    for y in range(radius):     # Generate kernel with formula
        kernel[x][y] = exp( -0.5 * (pow((x-mean)/sigma, 2.0) + pow((y-mean)/sigma,2.0)) ) / (2 * pi * sigma * sigma)
        magnitude += kernel[x][y]

for x in range(radius):     # normalize kernel
    for y in range(radius):
        kernel[x][y] /= magnitude

我知道内核可以工作,因为使用 OpenCV 的 filter2D 函数对我有用:

convolved = cv2.filter2D(img, -1, kernel)

我的问题是为什么我的convolve 函数不起作用?

【问题讨论】:

  • 只需将图像数据类型更改为 uint8 为 convolved = np.zeros((x, y),dtype=np.uint8) 或返回结果为 return convolved.astype(np.uint8)
  • @user8190410 谢谢你的工作!您介意解释一下它的作用/原因吗?
  • 因为如果您的图像数据类型是浮点数,那么它应该在 0 到 1 的范围内。这就是图像全白的原因

标签: python opencv image-processing convolution opencv-python


【解决方案1】:

您需要为图片指定 uint8 的数据类型

convolved = np.zeros((x, y))

制作

convolved = np.zeros((x, y), 'uint8')

我建议使用np.zeros_like() 方法,它接受一个数组并返回用零填充的数组,保留数组的原始数据类型,这样您就不必指定uint8:

convolved = np.zeros_like(img)

以上是最实用的,但也有一些替代方案

convolved = np.zeros((x, y)).astype('uint8')

convolved = np.uint8(np.zeros((x, y))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 2012-12-15
    • 1970-01-01
    • 2011-12-17
    • 2023-03-29
    • 2013-06-06
    • 1970-01-01
    • 2013-09-26
    相关资源
    最近更新 更多