Zi 字媒體
2017-07-25T20:27:27+00:00
OpenCV中圖像頻率域濾波(傅里葉變換 + 高通/低通 濾波)[python]
資料來源: https://mp.weixin.qq.com/s/w2D2q5Ym7HnPWPP7VOWjJw
CV API 原型
# 傅里叶变换函数
void cv::dft(
InputArray src,
OutputArray dst,
int flags = 0,
int nonzeroRows = 0
)
# 傅里叶逆变换函数
void cv::idft(
InputArray src,
OutputArray dst,
int flags = 0,
int nonzeroRows = 0
)
低通
def low_pass_filter_demo():
image = cv.imread("D:/images/test1.png", cv.IMREAD_GRAYSCALE)
img_float32 = np.float32(image)
rows, cols = image.shape
crow, ccol = rows//2 , cols//2
# FFT变换
dft = cv.dft(img_float32, flags = cv.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
# 创建低通滤波器,低频区域为 1, 高频区域为 0
mask = np.zeros((rows, cols, 2), np.uint8)
mask[crow-30:crow+30, ccol-30:ccol+30] = 1
# 滤波
fshift = dft_shift*mask
# 逆变换
f_ishift = np.fft.ifftshift(fshift)
img_back = cv.idft(f_ishift)
img_back = cv.magnitude(img_back[:,:,0],img_back[:,:,1])
cv.normalize(img_back, img_back, 0, 1.0, cv.NORM_MINMAX)
cv.imshow("input", image);
cv.imshow("low-pass-filter", img_back)
cv.imwrite("D:/low_pass.png", np.uint8(img_back*255))
cv.waitKey(0)
cv.destroyAllWindows()
高通
def high_pass_filter_demo():
image = cv.imread("D:/images/test1.png", cv.IMREAD_GRAYSCALE)
img_float32 = np.float32(image)
rows, cols = image.shape
crow, ccol = rows//2 , cols//2
# FFT变换
dft = cv.dft(img_float32, flags = cv.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
# 创建高通滤波器,低频区域为 0, 高频区域为 1
mask = np.ones((rows, cols, 2), np.uint8)
mask[crow-30:crow+30, ccol-30:ccol+30] = 0
# 滤波
fshift = dft_shift*mask
# 逆变换
f_ishift = np.fft.ifftshift(fshift)
img_back = cv.idft(f_ishift)
img_back = cv.magnitude(img_back[:,:,0],img_back[:,:,1])
cv.normalize(img_back, img_back, 0, 1.0, cv.NORM_MINMAX)
cv.imshow("input", image);
cv.imshow("high-pass-filter", img_back)
cv.imwrite("D:/high_pass.png", np.uint8(img_back*255))
cv.waitKey(0)
cv.destroyAllWindows()
寫了
5860316篇文章,獲得
23313次喜歡