import numpy as np
from scipy.signal import convolve2d

def convolve_gray_image(image, kernel):
    # 获取图像的尺寸
    height, width = image.shape
    
    # 获取卷积核的尺寸
    kernel_height, kernel_width = kernel.shape
    
    # 计算卷积结果的尺寸
    output_height = height - kernel_height + 1
    output_width = width - kernel_width + 1
    
    # 创建一个空的输出图像
    output_image = np.zeros((output_height, output_width))
    
    # 对图像进行卷积计算
    for i in range(output_height):
        for j in range(output_width):
            output_image[i, j] = np.sum(image[i:i+kernel_height, j:j+kernel_width] * kernel)
    
    return output_image

# 读取灰度图像
image = np.array([[1, 2, 3, 4, 5],
                  [6, 7, 8, 9, 10],
                  [11, 12, 13, 14, 15],
                  [16, 17, 18, 19, 20],
                  [21, 22, 23, 24, 25]])

# 定义卷积核
kernel = np.array([[1, 0, -1],
                   [2, 0, -2],
                   [1, 0, -1]])

# 进行卷积计算
output_image = convolve_gray_image(image, kernel)

print(output_image)
Python实现灰度图像卷积计算及代码示例

原文地址: https://www.cveoy.top/t/topic/fP3o 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录