图像的傅里叶变换:
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. Spark集成的包与引入包冲突

    今天在编写Spark应用的时候,想把处理结果输出为JSON字符串,查到Java比较常用的JSON处理包gson,按照其API编写代码后运行程序,总是出现"NoSuchMethodExcept ...

  2. Java数据结构之单向环形链表(解决Josephu约瑟夫环问题)

    1.Josephu(约瑟夫.约瑟夫环)问题: 设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m ...

  3. Element-ui 使用详细介绍

    一.后台搭建 使用 vue-admin-template 来快速搭建后台管理,它包含了 Element UI & axios & iconfont & permission c ...

  4. mysql数据库问题———登录进去无法操作显示You must reset your password using ALTER USER statement before executing this statement

    linux操作mysql数据库,可以登陆进去,但是操作所有命令都显示You must reset your password using ALTER USER statement before exe ...

  5. PHP批量导入excell表格到mysql数据库

    PHP批量导入excell表格到mysql数据库,本人通过亲自测试,在这里分享给大家 1,下载 php  excell类库 网上搜索可以下载,这里不写地址 2,建html文件 <form met ...

  6. Could not locate executable null\bin\winutils.exe in the Hadoop binaries解决方式

    1.  问题: 2.  问题解决: 仔细查看报错是缺少winutils.exe程序. Hadoop都是运行在Linux系统下的,在windows下eclipse中运行mapreduce程序,要首先安装 ...

  7. mysql之sql性能调优

    sql调优大致分为两步:1 如何定位慢查询   2 如何优化sql语句. 一:定位慢查询 -- 显示到mysql数据库的连接数 -- show status like 'connections'; - ...

  8. c# 杀死占用某个文件的进程

    原文:c# 杀死占用某个文件的进程 需要使用微软提供的工具Handle.exe string fileName = @"H:\abc.dll";//要检查被那个进程占用的文件 Pr ...

  9. LeetCode-239-剑指offer-滑动窗口的最大值-队列与栈-python

    给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值.例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6, ...

  10. 剑指offer-用两个栈来实现一个队列-队列与栈-python

    用两个栈来实现一个队列,完成队列的Push和Pop操作. 队列中的元素为int类型. 思路:使用两个栈,stackA 用来接收node stackB 用来接收 stackA 的出栈 # -*- cod ...