最大值滤波器和最小值滤波器的python代码
时间: 2023-11-13 15:03:28 浏览: 71
Python各种滤波器代码
4星 · 用户满意度95%
最大值滤波器代码:
```python
import cv2
import numpy as np
def max_filter(img, kernel_size):
# padding the image with zeros
pad_size = kernel_size // 2
padded_img = np.pad(img, ((pad_size, pad_size), (pad_size, pad_size), (0, 0)), mode='constant')
# create the kernel
kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
# apply the maximum filter
max_filtered = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
max_val = np.max(padded_img[i:i+kernel_size, j:j+kernel_size])
max_filtered[i, j] = max_val
return max_filtered
# load the image
img = cv2.imread('image.jpg')
# apply the maximum filter
max_filtered = max_filter(img, 5)
# display the original and filtered images
cv2.imshow('Original Image', img)
cv2.imshow('Maximum Filtered Image', max_filtered)
cv2.waitKey(0)
```
最小值滤波器代码:
```python
import cv2
import numpy as np
def min_filter(img, kernel_size):
# padding the image with zeros
pad_size = kernel_size // 2
padded_img = np.pad(img, ((pad_size, pad_size), (pad_size, pad_size), (0, 0)), mode='constant')
# create the kernel
kernel = np.ones((kernel_size, kernel_size), dtype=np.uint8)
# apply the minimum filter
min_filtered = np.zeros_like(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
min_val = np.min(padded_img[i:i+kernel_size, j:j+kernel_size])
min_filtered[i, j] = min_val
return min_filtered
# load the image
img = cv2.imread('image.jpg')
# apply the minimum filter
min_filtered = min_filter(img, 5)
# display the original and filtered images
cv2.imshow('Original Image', img)
cv2.imshow('Minimum Filtered Image', min_filtered)
cv2.waitKey(0)
```
阅读全文