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] # 最后一列