首页 > 解决方案 > 简单的 Python 模糊卷积核函数生成奇怪的图像

问题描述

我正在编写一个自定义函数来使用卷积核对图像应用模糊。但是,当我显示图像时,会出现奇怪的结果。在某些方面似乎图像是倒置的,但我不知道为什么。这是原始图像:

原始图像

结果如下:

在此处输入图像描述

我已经尝试过重新编写代码,更改图像,更改模糊内核,打印并亲自通过眼睛进行许多卷积等。

import cv2
import numpy as np
import matplotlib.pyplot as plt

def showImage(image):
    plt.imshow(image, cmap='gray')
    plt.show()


def gaussianBlur(image):
    tempImage = image.copy()
    tempImage = np.pad(tempImage, 1, "constant")

    showImage(tempImage)
    max = 0
    i = 0
    for x in range(1, len(image)-1):
        for y in range(1, len(image[0])-1):
            roi = image[x-1:x+2, y-1:y+2]
            kernel = np.array([
                [0.0625, 0.125, 0.0625],
                [0.125, 0.25, 0.125],
                [0.0625, 0.125, 0.0625]
            ])

            if np.matmul(roi, kernel).sum() > max:
                max = np.matmul(roi, kernel).sum()
            tempImage[x][y] = np.matmul(roi, kernel).sum()

            i += 1

            print(np.matmul(roi, kernel).sum())
            # if(i % 1000 == 0):
            #     showImage(tempImage)

    divAmount = max / 255

    for x in range(1, len(image)-1):
            for y in range(1, len(image[0])-1):
                tempImage[x][y] = tempImage[x][y] / divAmount
    return tempImage.tolist()

# Load and view the image
image = cv2.imread("image_1_small.jpg", 0)
showImage(image)

# Apply Blur
image = gaussianBlur(image)
print(image)
# image = cv2.GaussianBlur(image, (5, 5), 0)
showImage(image)

预期的结果应该看起来像原始图像只是模糊的。

标签: pythonnumpyopencvmachine-learningconvolution

解决方案


这是由溢出引起的。你计算卷积错误。使用 np.multiply 代替 np.matmul。


推荐阅读