数字图像的空间域滤波和频域滤波

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

数字图像的空间域滤波和频域滤波

三、实验过程

1. 平滑空间滤波:

1) 读出一幅图像,给这幅图像分别加入椒盐噪声和高斯噪声后并与前一张图显示在同一图像窗口中。

椒盐噪声:

def salt_pepperNoise(src):

dst = src.copy()

num = 1000 # 1000个噪声点

ndim = np.ndim(src)

row, col = np.shape(src)[0:2]

for i in range(num):

x = np.random.randint(0, row) # 随机生成噪声点位置

y = np.random.randint(0, col)

indicator = np.random.randint(0, 2)

# 灰度图像

if ndim == 2:

if indicator == 0:

dst[x, y] = 0

else:

dst[x, y] = 255

# 彩色图像

elif ndim == 3:

if indicator == 0:

dst[x, y, :] = 0

else:

dst[x, y, :] = 255

return dst

高斯噪声:

def addGaussianNoise(image,sigma):

mean = 0.0

row, col ,ch= image.shape

gauss = np.random.normal(mean, sigma, (row, col,ch))

gauss = gauss.reshape(row, col,ch)

noisy = image + gauss

return noisy.astype(np.uint8)

2) 对加入噪声图像选用不同的平滑(低通)模板做运算,对比不同模板所形成的效果,要求在同一窗口中显示。

加入椒盐噪声后图像的滤波:

img1 =cv2.imread("D:\\mote.jpg",0)

img=img1[100:300]

src =salt_pepperNoise(img)

cv2.imshow("origin",src)

dst = cv2.blur(src,(3,3)) #均值滤波模板

cv2.imshow("blur",dst)

dst1 = cv2.medianBlur(src,5) #中值滤波

cv2.imshow("medianBlur",dst1)

dst2 = cv2.GaussianBlur(src,(3,3),0) #高斯滤波

cv2.imshow("GaussianBlur",dst2)

cv2.waitKey(0)

cv2.destroyAllWindows()

3) 进行低通滤波,显示处理后的图像。

import cv2

import numpy as np

def function(img):

h,w=img.shape

newimg=np.zeros((h,w),np.uint8)

img2=np.fft.fft2(img)

fshift = np.fft.fftshift(img2)

st=fshift.copy()

h,w=fshift.shape

sh=h/2

sw=w/2

r=40

for i in range(h):

for j in range(w):

if ((sh - i) * (sh - i) + (sw - j) * (sw - j)) <= r * r: newimg[i, j] = 255

tmp = 1

else:

tmp = 0

st[i, j] = tmp * fshift[i, j]

sl=np.fft.ifftshift(st)

x2=np.fft.ifft2(sl)

x3=np.uint8(np.real(x2))

return newimg,x3

img=cv2.imread('D:\\mote.jpg',0)

img1,img2=function(img)

cv2.imshow("image",img)

cv2.imshow("low pass filtering",img2)

cv2.waitKey(0)

4) 显示均值处理后的图像。

代码:

import cv2

import matplotlib.pyplot as plt

img = cv2.imread('D:\\mote.jpg',0) #直接读为灰度图像

blur = cv2.blur(img,(3,5))#模板大小3*5

plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色,另一种彩色bgr plt.title('img')

plt.xticks([]), plt.yticks([])

plt.subplot(1,2,2),plt.imshow(blur,'gray')

plt.title('blur')

plt.xticks([]), plt.yticks([])

plt.show()

相关文档
最新文档