import numpy as np import cv2

def convolution(image, kernel): height, width = image.shape k_height, k_width = kernel.shape pad_height = k_height // 2 pad_width = k_width // 2

padded_image = np.pad(image, ((pad_height, pad_height), (pad_width, pad_width)), 'constant')
convolved_image = np.zeros_like(image)

for i in range(height):
    for j in range(width):
        convolved_image[i, j] = np.sum(padded_image[i:i+k_height, j:j+k_width] * kernel)

return convolved_image

Load the grayscale image

image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)

Define the kernel

kernel = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])

Perform convolution

convolved_image = convolution(image, kernel)

Display the original and convolved images

cv2.imshow('Original Image', image) cv2.imshow('Convolved Image', convolved_image) cv2.waitKey(0) cv2.destroyAllWindows()

Python 灰度图像卷积计算实现:代码示例与解释

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

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