图像的傅里叶变换:
import chardet
import numpy as np
import cv2 as cv
import cv2
from PIL import Image
import sys
from matplotlib import pyplot as plt

img = cv2.imread('D:/1/4.jpg',0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
magnitude_spectrum = 20*np.log(np.abs(fshift))

rows, cols = img.shape
crow,ccol = int(rows/2) , int(cols/2)
fshift[crow-30:crow+30, ccol-30:ccol+30] = 0
f_ishift = np.fft.ifftshift(fshift)
img_back = np.fft.ifft2(f_ishift)
img_back = np.abs(img_back)

plt.subplot(221),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(magnitude_spectrum, cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(223),plt.imshow(img_back) #恢复图像
plt.title('Result in JET'), plt.xticks([]), plt.yticks([])
plt.subplot(224),plt.imshow(img_back, cmap = 'gray')
plt.title('Image after HPF'), plt.xticks([]), plt.yticks([])
plt.show()

图像的噪声处理与去噪:
def add_noise(img):
rows,cols,dims=img.shape
for i in range(5000):
x=np.random.randint(0,rows)
y=np.random.randint(0,cols)
img[x,y,:]=1

#二值化处理,以128位界
def add1_noise(img):
rows,cols=img.shape
for i in range(rows):
for j in range(cols):
if (img[i,j]<=128):
img[i,j]=0
else:
img[i,j]=1

# 高斯噪声
def GaussieNoisy(image,sigma):
row,col,ch= image.shape
mean = 0
gauss = np.random.normal(mean,sigma,(row,col,ch))
gauss = gauss.reshape(row,col,ch)
noisy = image + gauss
return noisy.astype(np.uint8)

#椒盐噪声
def spNoisy(image,s_vs_p = 0.5,amount = 0.004):
row,col,ch = image.shape
out = np.copy(image)
num_salt = np.ceil(amount * image.size * s_vs_p)
coords = [np.random.randint(0, i - 1, int(num_salt)) for i in image.shape]
out[coords] = 1
num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in image.shape]
out[coords] = 0
return out

img=np.array(Image.open('D:/1/1.jpg'))
plt.figure()
plt.subplot(221)
plt.title("src_img")
plt.imshow(img)
plt.axis('off')

plt.subplot(222)
plt.title("noise_img")
add_noise(img)
plt.imshow(img)
plt.axis('off')

# # 图像二值化,像素值大于128的变为1,否则变为0
img2=np.array(Image.open('D:/1/1.jpg').convert('L'))
plt.subplot(223)
plt.title("noise2_img")
add1_noise(img2)
plt.imshow(img2)
plt.axis('off')

plt.subplot(224)
plt.title("GaussieNoisy")
img3=np.array(Image.open('D:/1/1.jpg'))
plt.imshow(GaussieNoisy(img3,25))
plt.axis('off')
plt.show()

傅里叶变换与逆变换:
# 傅里叶变换:
# 傅里叶变换将低频信号放在了边缘,高频信号放在了中间,然而一副图像,
# 很明显的低频信号多而明显,所以讲低频信号移至中心

img = cv2.imread('D:/1/4.jpg',0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)#将频谱对称轴从左上角移至中心
# #对于负数可以求角度:
# # ph_f=np.angle(f)
# # ph_fshift = np.angle(fshift)
#取绝对值:将复数变化成实数
#取对数的目的为了将数据变化到较小的范围(比如0-255)
s1 = np.log(np.abs(f))
s2 = np.log(np.abs(fshift))
plt.subplot(221),plt.imshow(img,'gray'),plt.title('original')
plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(s2,'gray'),plt.title('center')
plt.xticks([]), plt.yticks([])
f1shift = np.fft.ifftshift(fshift)# 逆变换
img_back = np.fft.ifft2(f1shift)
img_back = np.abs(img_back)#出来的是复数,无法显示,求绝对值
plt.subplot(223),plt.imshow(img_back,'gray'),plt.title('img back')
plt.xticks([]), plt.yticks([])
plt.show()

傅里叶变换进行滤波:
傅里叶变换实现高通录滤波:
图像在变换加移动中心后,从中间到外面,频率上依次是从低频到高频的,
那么我们如果把中间规定一小部分去掉,是不是相对于把低频信号去掉了呢?
这也就是相当于进行了高通滤波

低通滤波器:把上述模板中的1变成0,0变成1

def lowPassFilter(image, d):
f = np.fft.fft2(image)
fshift = np.fft.fftshift(f)
def make_transform_matrix(d):
transfor_matrix = np.zeros(image.shape)
center_point = tuple(map(lambda x: (x - 1) / 2, s1.shape))
for i in range(transfor_matrix.shape[0]):
for j in range(transfor_matrix.shape[1]):
def cal_distance(pa, pb):
from math import sqrt
dis = sqrt((pa[0] - pb[0]) ** 2 + (pa[1] - pb[1]) ** 2)
return dis
dis = cal_distance(center_point, (i, j))
if dis <= d:
transfor_matrix[i, j] = 1
else:
transfor_matrix[i, j] = 0
return transfor_matrix

d_matrix = make_transform_matrix(d)
new_img = np.abs(np.fft.ifft2(np.fft.ifftshift(fshift * d_matrix)))
return new_img

def highPassFilter(image,d):
f = np.fft.fft2(image)
fshift = np.fft.fftshift(f)
def make_transform_matrix(d):
transfor_matrix = np.zeros(image.shape)
center_point = tuple(map(lambda x:(x-1)/2,s1.shape))
for i in range(transfor_matrix.shape[0]):
for j in range(transfor_matrix.shape[1]):
def cal_distance(pa,pb):
from math import sqrt
dis = sqrt((pa[0]-pb[0])**2+(pa[1]-pb[1])**2)
return dis
dis = cal_distance(center_point,(i,j))
if dis <= d:
transfor_matrix[i,j]=0
else:
transfor_matrix[i,j]=1
return transfor_matrix
d_matrix = make_transform_matrix(d)
new_img = np.abs(np.fft.ifft2(np.fft.ifftshift(fshift*d_matrix)))
return new_img

img = cv2.imread('D:/1/5.jpg',0)
plt.figure()
plt.subplot(221)
plt.imshow(img,cmap="gray")
plt.axis("off")
plt.title('gray')

f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
s1 = np.log(np.abs(fshift))
plt.subplot(222)
plt.imshow(s1,'gray')
plt.axis("off")
plt.title('Frequency Domain')

plt.subplot(223)
plt.imshow(lowPassFilter(img,100),cmap="gray")
plt.axis("off")
plt.title('lowPassFilter')

plt.subplot(224)
plt.imshow(highPassFilter(img,50),cmap="gray")
plt.axis("off")
plt.title('highPassFilter')
plt.show()

图像噪声与去噪算法
中值滤波
概述: 中值滤波是一种非线性空间滤波器, 它的响应基于图像滤波器包围的图像区域中像素的统计排序,
然后由统计排序结果的值代替中心像素的值.中值滤波器将其像素邻域内的灰度中值代替代替该像素的值. 中值滤波器的使用非常普遍,
这是因为对于一定类型的随机噪声, 它提供了一种优秀的去噪能力,比小尺寸的均值滤波器模糊程度明显要低. 中值滤波器对处理脉冲噪声(也称椒盐噪声)非常有效,
因为该噪声是以黑白点叠加在图像上面的.

均值滤波
概述: 均值滤波器的输出是包含在滤波掩模领域内像素的简单平均值.
均值滤波器最常用的目的就是减噪. 然而, 图像边缘也是由图像灰度尖锐变化带来的特性,
所以均值滤波还是存在不希望的边缘模糊负面效应.

# 图片修复程序1(实现水印去除):修复白色区域
img = cv2.imread("D:/1/2.jpg")
hight, width, depth = img.shape[0:3]
# 图片二值化处理,把[240, 240, 240]~[255, 255, 255]以外的颜色变成0
thresh = cv2.inRange(img, np.array([240, 240, 240]), np.array([255, 255, 255]))
# 创建形状和尺寸的结构元素
kernel = np.ones((3, 3), np.uint8)
# 扩张待修复区域
hi_mask = cv2.dilate(thresh, kernel, iterations=1)
specular = cv2.inpaint(img, hi_mask, 5, flags=cv2.INPAINT_TELEA)
cv2.namedWindow("Image", 0)
cv2.resizeWindow("Image", int(width / 2), int(hight / 2))
cv2.imshow("Image", img)
cv2.namedWindow("newImage", 0)
cv2.resizeWindow("newImage", int(width / 2), int(hight / 2))
cv2.imshow("newImage", specular)
cv2.waitKey(0)
cv2.destroyAllWindows()

频域高斯滤波:
def GaussianHighFilter(image,d):
f = np.fft.fft2(image)
fshift = np.fft.fftshift(f)
def make_transform_matrix(d):
transfor_matrix = np.zeros(image.shape)
center_point = tuple(map(lambda x:(x-1)/2,s1.shape))
for i in range(transfor_matrix.shape[0]):
for j in range(transfor_matrix.shape[1]):
def cal_distance(pa,pb):
from math import sqrt
dis = sqrt((pa[0]-pb[0])**2+(pa[1]-pb[1])**2)
return dis
dis = cal_distance(center_point,(i,j))
transfor_matrix[i,j] = 1-np.exp(-(dis**2)/(2*(d**2)))
return transfor_matrix
d_matrix = make_transform_matrix(d)
new_img = np.abs(np.fft.ifft2(np.fft.ifftshift(fshift*d_matrix)))
return new_img

def GaussianLowFilter(image,d):
f = np.fft.fft2(image)
fshift = np.fft.fftshift(f)
def make_transform_matrix(d):
transfor_matrix = np.zeros(image.shape)
center_point = tuple(map(lambda x:(x-1)/2,s1.shape))
for i in range(transfor_matrix.shape[0]):
for j in range(transfor_matrix.shape[1]):
def cal_distance(pa,pb):
from math import sqrt
dis = sqrt((pa[0]-pb[0])**2+(pa[1]-pb[1])**2)
return dis
dis = cal_distance(center_point,(i,j))
transfor_matrix[i,j] = np.exp(-(dis**2)/(2*(d**2)))
return transfor_matrix
d_matrix = make_transform_matrix(d)
new_img = np.abs(np.fft.ifft2(np.fft.ifftshift(fshift*d_matrix)))
return new_img

img = cv2.imread('D:/1/5.jpg',0)
f = np.fft.fft2(img)
fshift = np.fft.fftshift(f)
s1 = np.log(np.abs(fshift))

plt.figure()
plt.subplot(221)
plt.imshow(img,cmap="gray")
plt.axis("off")
plt.title('gray')

plt.subplot(222)
plt.axis("off")
plt.imshow(GaussianHighFilter(img,10),cmap="gray")
plt.title('GaussianHighFilter')

plt.subplot(223)
plt.axis("off")
plt.imshow(GaussianLowFilter(img,50),cmap="gray")
plt.title('GaussianLowFilter')

plt.show()

空间域的高斯滤波
def GaussianOperator(roi):
GaussianKernel = np.array([[1,2,1],[2,4,2],[1,2,1]])
result = np.sum(roi*GaussianKernel/16)
return result

def GaussianSmooth(image):
new_image = np.zeros(image.shape)
image = cv2.copyMakeBorder(image,1,1,1,1,cv2.BORDER_DEFAULT)
for i in range(1,image.shape[0]-1):
for j in range(1,image.shape[1]-1):
new_image[i-1,j-1] =GaussianOperator(image[i-1:i+2,j-1:j+2])
return new_image.astype(np.uint8)

img=cv.imread("D:/1/5.jpg",0)
new_apple = GaussianSmooth(img)
plt.subplot(121)
plt.axis("off")
plt.title("origin image")
plt.imshow(img,cmap="gray")
plt.subplot(122)
plt.axis("off")
plt.title("Gaussian image")
plt.imshow(img,cmap="gray")
plt.subplot(122)
plt.axis("off")
plt.show()

相关函数说明:
img[i,:] = im[j,:] # 将第 j 行的数值赋值给第 i 行
img[:,i] = 100 # 将第 i 列的所有数值设为 100
img[:100,:50].sum() # 计算前 100 行、前 50 列所有数值的和
img[50:100,50:100] # 50~100 行,50~100 列(不包括第 100 行和第 100 列)
img[i].mean() # 第 i 行所有数值的平均值
img[:,-1] # 最后一列
 
原文链接:https://blog.csdn.net/linkingfei/article/details/87433352

python图像处理——频率域增强的更多相关文章

  1. PIE SDK频率域滤波

    1.算法功能简介 频率域滤波的基本工作流程为:空间域图像的傅里叶变换→频率域图像→设计滤波器→傅里叶逆变换→其他应用. 低通滤波,对频率域的图像通过滤波器削弱或抑制高频部分而保留低频部分的滤波方法,可 ...

  2. python数字图像处理(四) 频率域滤波

    import matplotlib.pyplot as plt import numpy as np import cv2 %matplotlib inline 首先读入这次需要使用的图像 img = ...

  3. 跟我学Python图像处理丨带你掌握傅里叶变换原理及实现

    摘要:傅里叶变换主要是将时间域上的信号转变为频率域上的信号,用来进行图像除噪.图像增强等处理. 本文分享自华为云社区<[Python图像处理] 二十二.Python图像傅里叶变换原理及实现> ...

  4. 跟我学Python图像处理丨傅里叶变换之高通滤波和低通滤波

    摘要:本文讲解基于傅里叶变换的高通滤波和低通滤波. 本文分享自华为云社区<[Python图像处理] 二十三.傅里叶变换之高通滤波和低通滤波>,作者:eastmount . 一.高通滤波 傅 ...

  5. Python图像处理库:Pillow 初级教程

    Python图像处理库:Pillow 初级教程 2014-09-14 翻译 http://pillow.readthedocs.org/en/latest/handbook/tutorial.html ...

  6. Python图像处理库(1)

    转自:http://www.ituring.com.cn/tupubarticle/2024 第 1 章 基本的图像操作和处理 本章讲解操作和处理图像的基础知识,将通过大量示例介绍处理图像所需的 Py ...

  7. Python 图像处理 OpenCV (12): Roberts 算子、 Prewitt 算子、 Sobel 算子和 Laplacian 算子边缘检测技术

    前文传送门: 「Python 图像处理 OpenCV (1):入门」 「Python 图像处理 OpenCV (2):像素处理与 Numpy 操作以及 Matplotlib 显示图像」 「Python ...

  8. Python 图像处理 OpenCV (13): Scharr 算子和 LOG 算子边缘检测技术

    前文传送门: 「Python 图像处理 OpenCV (1):入门」 「Python 图像处理 OpenCV (2):像素处理与 Numpy 操作以及 Matplotlib 显示图像」 「Python ...

  9. Python 图像处理 OpenCV (16):图像直方图

    前文传送门: 「Python 图像处理 OpenCV (1):入门」 「Python 图像处理 OpenCV (2):像素处理与 Numpy 操作以及 Matplotlib 显示图像」 「Python ...

随机推荐

  1. python 封装dlib模型进行人脸识别系统的登录认证

    1.直接上干货 #!/usr/bin/python # -*- coding: utf-8 -*- import time import dlib import numpy as np class f ...

  2. kafka学习(七)

    跨集群数据镜像 跨集群镜像的使用场景 1.区域集群和中心集群 2.冗余,发生紧急情况下使用第二个集群,保存相同的数据. 3.云迁移   多集群架构   跨集群中心通信的一些现实情况 1.高延迟 2.有 ...

  3. windows系统IO性能测试

    关键词:sql server io测试 下载链接:http://www.onlinedown.net/soft/57364.htm CrystalDiskMark(硬盘检测工具),一个测试你的硬盘或者 ...

  4. 字符串中的replace方法

    String.prototype.replace() 该方法作为字符串中非常常用的方法, 今天我们具体介绍一下它的用法 语法格式 someString.replace(regxp | substr, ...

  5. python3—廖雪峰之练习(二)

    函数的参数练习 请定义一个函数quadratic(a, b, c), 接收3个参数,返回一元二次方程 : $ ax^2+b+c=0 $ 的两个解 提示:计算平方根可以调用math.sqrt()函数: ...

  6. 腾讯云从零搭建PHP运行环境

    一.首先我们得注册腾讯云,租用一台服务器,我选择的是CentOS 7.2 64位,这时候会给你这台主机的公网IP和内网IP,以及这台主机的用户名及密码. 二.我们可以使用腾讯云网页上自带的登录按钮进行 ...

  7. 【源码解读】pix2pix(一):训练

    源码地址:https://github.com/mrzhu-cool/pix2pix-pytorch 相比于朱俊彦的版本,这一版更加简单易读 训练的代码在train.py,开头依然是很多代码的共同三板 ...

  8. ECMAScript 6 学习笔记(一)

    ECMAScript 6简介 ECMAScript 6.0(以下简称ES6)是JavaScript语言的下一代标准,已经在2015年6月正式发布了.它的目标,是使得JavaScript语言可以用来编写 ...

  9. hashlib模块和logging模块

    hashlib Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等. 我们以常见的摘要算法MD5为例,计算出一个字符串的MD5值: import hashlib m=hashli ...

  10. java web请求过程

    小技巧: 1.浏览器缓存 Ctrl+F5组合键刷新页面,浏览器会直接向目标URL发送请求,而不会使用浏览器缓存,并会在HTTP请求header中增加下面的请求头来告诉服务器不使用服务器缓存 发现在re ...