opencv 维纳滤波
时间: 2023-11-23 22:58:16 浏览: 218
维纳滤波是一种基于频域的滤波方法,可以用于去除图像中的噪声。在OpenCV中,可以使用cv2.filter2D()函数来实现维纳滤波。具体步骤如下:
1.读取图像并将其转换为灰度图像。
```python
import cv2
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
```
2.对图像进行傅里叶变换,并计算频谱图。
```python
import numpy as np
dft = cv2.dft(np.float32(gray), flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
```
3.根据噪声的功率谱密度和信噪比,计算维纳滤波器的频率响应。
```python
H = np.zeros_like(dft_shift, dtype=np.float32)
rows, cols = gray.shape
snr = 10 # 信噪比
noise_power = 0.01 * np.var(gray) # 噪声功率谱密度
for i in range(rows):
for j in range(cols):
H[i, j] = 1 / (1 + snr / (magnitude_spectrum[i, j] ** 2 / noise_power))
```
4.将维纳滤波器的频率响应与图像的傅里叶变换相乘,得到滤波后的傅里叶变换结果。
```python
filtered_dft_shift = H * dft_shift
```
5.对滤波后的傅里叶变换结果进行傅里叶逆变换,得到滤波后的图像。
```python
filtered_dft = np.fft.ifftshift(filtered_dft_shift)
filtered_img = cv2.idft(filtered_dft)
filtered_img = cv2.magnitude(filtered_img[:, :, 0], filtered_img[:, :, 1])
filtered_img = cv2.normalize(filtered_img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
```
完整代码如下:
```python
import cv2
import numpy as np
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dft = cv2.dft(np.float32(gray), flags=cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
H = np.zeros_like(dft_shift, dtype=np.float32)
rows, cols = gray.shape
snr = 10 # 信噪比
noise_power = 0.01 * np.var(gray) # 噪声功率谱密度
for i in range(rows):
for j in range(cols):
H[i, j] = 1 / (1 + snr / (magnitude_spectrum[i, j] ** 2 / noise_power))
filtered_dft_shift = H * dft_shift
filtered_dft = np.fft.ifftshift(filtered_dft_shift)
filtered_img = cv2.idft(filtered_dft)
filtered_img = cv2.magnitude(filtered_img[:, :, 0], filtered_img[:, :, 1])
filtered_img = cv2.normalize(filtered_img, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
cv2.imshow('Original Image', img)
cv2.imshow('Filtered Image', filtered_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
阅读全文