共计 1339 个字符,预计需要花费 4 分钟才能阅读完成。
实验内容:图像空域与频域的平滑、锐化处理的模板方法
空域的平滑和锐化
导入图像
import cv2 as cv
import numpy as np
import random
import matplotlib.pyplot as plt
img = cv.imread("1.png", 1)
img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
# cv.imshow("img.png", img)
plt.imshow(img)
添加随机噪声
# 加噪声
(rows, cols, chn) = img.shape
for i in range(100):
x = np.random.randint(0, rows)
y = np.random.randint(0, cols)
img[x, y, :] = random.randint(0, 255)
# cv.imshow("noise", img)
plt.imshow(img)
空域平滑
# 以中值滤波为例
blur_img = cv.medianBlur(img, 3)
plt.imshow(blur_img)
空域锐化
gray_img = cv.cvtColor(blur_img, cv.COLOR_RGB2GRAY)
# laplacian_img = cv.Laplacian(blur_img, cv.CV_64F)
# kernel4 = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], dtype=int)
kernel8 = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]], dtype=int)
filter_img = cv.filter2D(gray_img, -1, kernel8)
plt.imshow(filter_img, cmap = 'gray')
频域的平滑和锐化
频域平滑
gaussian_blur_img = cv.GaussianBlur(img, (11, 11), sigmaX=20)
plt.imshow(gaussian_blur_img)
频域锐化
gray_gaussian_blur_img = cv.cvtColor(gaussian_blur_img, cv.COLOR_RGB2GRAY)
dft = cv.dft(np.float32(gray_gaussian_blur_img), flags=cv.DFT_COMPLEX_OUTPUT)
fshift = np.fft.fftshift(dft)
row, col = gray_gaussian_blur_img.shape
midrow, midcol = int(row / 2), int(col / 2)
mask = np.ones((row, col, 2), np.uint8)
mask[midrow-30 : midrow+30, midcol-30 : midcol+30] = 0
f = fshift * mask
ishift = np.fft.ifftshift(f)
hight_img = cv.idft(ishift)
hight_img = cv.magnitude(hight_img[:, :, 0], hight_img[:, :, 1])
plt.imshow(hight_img, cmap='gray')
正文完