不使用opencv库用python编写对于高斯滤波后的图像像素求梯度代码
时间: 2023-05-20 19:04:06 浏览: 100
以下是一个简单的 Python 代码,用于计算高斯滤波后的图像像素的梯度:
```python
import numpy as np
def gaussian_filter(image, sigma):
# 高斯滤波
kernel_size = int(2 * np.ceil(3 * sigma) + 1)
kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size // 2
for i in range(kernel_size):
for j in range(kernel_size):
x, y = i - center, j - center
kernel[i, j] = np.exp(-(x ** 2 + y ** 2) / (2 * sigma ** 2))
kernel /= np.sum(kernel)
filtered_image = np.zeros_like(image)
padded_image = np.pad(image, ((center, center), (center, center)), mode='edge')
for i in range(center, padded_image.shape[0] - center):
for j in range(center, padded_image.shape[1] - center):
filtered_image[i - center, j - center] = np.sum(padded_image[i - center:i + center + 1, j - center:j + center + 1] * kernel)
return filtered_image
def gradient(image):
# 计算梯度
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
sobel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]])
filtered_x = np.zeros_like(image)
filtered_y = np.zeros_like(image)
padded_image = np.pad(image, ((1, 1), (1, 1)), mode='edge')
for i in range(1, padded_image.shape[0] - 1):
for j in range(1, padded_image.shape[1] - 1):
filtered_x[i - 1, j - 1] = np.sum(padded_image[i - 1:i + 2, j - 1:j + 2] * sobel_x)
filtered_y[i - 1, j - 1] = np.sum(padded_image[i - 1:i + 2, j - 1:j + 2] * sobel_y)
gradient_magnitude = np.sqrt(filtered_x ** 2 + filtered_y ** 2)
gradient_direction = np.arctan2(filtered_y, filtered_x)
return gradient_magnitude, gradient_direction
# 读取图像
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE)
# 高斯滤波
sigma = 1.5
filtered_image = gaussian_filter(image, sigma)
# 计算梯度
gradient_magnitude, gradient_direction = gradient(filtered_image)
# 显示结果
cv2.imshow('Original Image', image)
cv2.imshow('Filtered Image', filtered_image)
cv2.imshow('Gradient Magnitude', gradient_magnitude)
cv2.imshow('Gradient Direction', gradient_direction)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
这个代码使用了 NumPy 库来进行矩阵计算,但没有使用 OpenCV 库。它首先对图像进行高斯滤波,然后计算每个像素的梯度幅值和方向。最后,它将结果显示在屏幕上。
阅读全文