乐趣区

关于python:数字图像处理空间滤波

平滑线性空间滤波器
盒状态滤波
import numpy as np
from scipy import signal
from skimage import data, io
from matplotlib import pyplot as plt

定义二维灰度图像的空间滤波函数

def correl2d(img, window):

s = signal.correlate2d(img, window, mode='same', boundary='fill')
return s.astype(np.uint8)

img = data.grass()

img = io.imread(‘tomato.jpg’)

3*3 盒状滤波模板

window1 = np.ones((3, 3)) / (3 ** 2)

5*5 盒状滤波模板

window2 = np.ones((5, 5)) / (5 ** 2)

9*9 盒状滤波模板

window3 = np.ones((9, 9)) / (9 ** 2)

生成滤波后果

img1 = correl2d(img, window1)
img2 = correl2d(img, window2)
img3 = correl2d(img, window3)
plt.figure()
plt.imshow(img)
plt.figure()
plt.imshow(img1)
plt.figure()
plt.imshow(img2)
plt.figure()
plt.imshow(img3)
plt.show()
高斯平滑滤波
应用 data 自带图像
import numpy as np
from scipy import signal
from skimage import data, io
from matplotlib import pyplot as plt
import math

定义二维灰度图像的空间滤波函数

def correl2d(img, window):

#mode='same' 示意输入尺寸等于输出尺寸
#boundary=‘fill’[贝宝](https://www.gendan5.com/wallet/PayPal.html)示意滤波前,用常量值填充原始图像的边缘,默认常量值为 0
s = signal.correlate2d(img, window, mode='same', boundary='fill')
return s.astype(np.uint8)

定义二维高斯函数

def gauss(i, j, sigma):

return 1 / (2 * math.pi * sigma ** 2) * math.exp(-(i ** 2 + j ** 2) / (2 * sigma ** 2))

定义 radius*radius 的高斯平滑模板

def gauss_window(radius, sigma):

window = np.zeros((radius * 2 + 1, radius * 2 + 1))
for i in range(-radius, radius + 1):
    for j in range(-radius, radius + 1):
        window[i + radius][j + radius] = gauss(i, j, sigma)
return window / np.sum(window)

img = data.grass()

3*3 高斯平滑滤波模板

window1 = gauss_window(3, 1.0)

5*5 高斯平滑滤波模板

window2 = gauss_window(5, 1.0)

9*9 高斯平滑滤波模板

window3 = gauss_window(9, 1.0)

生成滤波后果

img1 = correl2d(img, window1)
img2 = correl2d(img, window2)
img3 = correl2d(img, window3)
plt.figure()
plt.imshow(img, cmap=’gray’)
plt.figure()
plt.imshow(img1, cmap=’gray’)
plt.figure()
plt.imshow(img2, cmap=’gray’)
plt.figure()
plt.imshow(img3, cmap=’gray’)
plt.show()
导入内部图像:
import cv2
import numpy as np
from scipy import ndimage
img1 = cv2.imread(‘tomato.jpg’)
gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY) # 灰色
cv2.imwrite(‘gray.jpg’, gray)
kernel_3x3 = np.array([

[1, 2, 1],
[2, 4, 2],
[1, 2, 1]

])
kernel_5x5 = np.array([

[1, 4, 7, 4, 1],
[4, 16, 26, 16, 4],
[7, 26, 41, 26, 7],
[4, 16, 26, 16, 4],
[1, 4, 7, 4, 1]

])
kernel_3x3 = kernel_3x3 / kernel_3x3.sum() # 加权均匀
kernel_5x5 = kernel_5x5 / kernel_5x5.sum() # 加权均匀
img = cv2.imread(“tomato.jpg”, 0)
k3 = ndimage.convolve(img, kernel_3x3)
k5 = ndimage.convolve(img, kernel_5x5)
cv2.imshow(“3×3”, k3)
cv2.imshow(“5×5”, k5)
cv2.imwrite(‘k3.jpg’, k3)
cv2.imwrite(‘k5.jpg’, k5)
cv2.waitKey()

退出移动版