OpenCV_图像处理
灰度图
import cv2 #opencv读取的格式是BGR
img=cv2.imread('cat.jpg')
img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img_gray.shape
cv2.imshow("img_gray", img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
HSV
H - 色调(主波长)。
S - 饱和度(纯度/颜色的阴影)。
V值(强度
cv2.imshow("hsv", hsv)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
图像阈值
ret, dst = cv2.threshold(src, thresh, maxval, type)
-
src: 输入图,只能输入单通道图像,通常来说为灰度图
-
dst: 输出图- - thresh: 阈值
-
maxval: 当像素值超过了阈值(或者小于阈值,根据type来决定),所赋予的值
-
type:二值化操作的类型,包含以下5种类型:
cv2.THRESH_BINARY; cv2.THRESH_BINARY_INV; cv2.THRESH_TRUNC;
cv2.THRESH_TOZERO;cv2.THRESH_TOZERO_INV-
cv2.THRESH_BINARY 超过阈值部分取maxval(最大值),否则取0
-
cv2.THRESH_BINARY_INV THRESH_BINARY的反转
-
cv2.THRESH_TRUNC大于阈值部分设为阈值,否则不变cv2.THRESH_TOZERO 大于阈值部分不改变,否则设为0
-
cv2.THRESH_TOZERO_INV THRESH_TOZERO的反转
-
ret, thresh1 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
ret, thresh2 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY_INV)
ret, thresh3 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TRUNC)
ret, thresh4 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO)
ret, thresh5 = cv2.threshold(img_gray, 127, 255, cv2.THRESH_TOZERO_INV)
titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']
images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]
for i in range(6):
plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
图像平滑处理
1.均值滤波
简单的平均卷积操作
一般都是奇数矩阵
blur = cv2.blur(img, (3, 3))
- 1
2.方框滤波
参数解释:
-1:颜色通道一样
normalize=True:效果同上
normalize=False:>255全部赋为255
# 方框滤波
# 基本和均值一样,可以选择归一化
box = cv2.boxFilter(img,-1,(3,3), normalize=True)
box = cv2.boxFilter(img,-1,(3,3), normalize=False)
- 1
- 2
- 3
- 4
- 5
3.高斯滤波
高斯模糊的卷积核里的数值是满足高斯分布,相当于更重视中间的
第三个参数,中间最重要的设为1
aussian = cv2.GaussianBlur(img, (5, 5), 1)
- 1
4.中值滤波
相当于用中值代替
完全去噪
第二个参数:5表示找5*5矩阵中间那个数
median = cv2.medianBlur(img, 5)
- 1
总结与对比展示
import cv2
import numpy as np
img = cv2.imread('img/lenaNoise.png')
# 均值滤波
blur = cv2.blur(img, (3, 3))
# 方框滤波
box = cv2.boxFilter(img,-1,(3,3), normalize=False)
# 高斯滤波
aussian = cv2.GaussianBlur(img, (5, 5), 1)
# 中值滤波
median = cv2.medianBlur(img, 5) # 中值滤波
# 展示所有的
res = np.hstack((blur,aussian,median)) # 水平显示
# res = np.vstack((blur,box,aussian,median)) # 垂直显示
cv2.imshow('median vs average', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
形态学
腐蚀操作
iterations:迭代次数
cv2.erode(img,kernel,iterations = 1)
kernel = np.ones((3,3),np.uint8)
erosion = cv2.erode(img,kernel,iterations = 1)
- 1
- 2
膨胀操作
cv2.dilate(dige_erosion,kernel,iterations = 1)
kernel = np.ones((3,3),np.uint8)
dige_dilate = cv2.dilate(dige_erosion,kernel,iterations = 1)
- 1
- 2
开运算与闭运算
开:先腐蚀,再膨胀
cv2.MORPH_OPEN
cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
kernel = np.ones((5,5),np.uint8)
opening = cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)
- 1
- 2
闭:先膨胀,再腐蚀
cv2.MORPH_CLOSE
cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
kernel = np.ones((5,5),np.uint8)
cv2.MORPH_CLOSE
closing = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)
- 1
- 2
- 3
梯度
梯度=膨胀-腐蚀
cv2.MORPH_GRADIENT
cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel)
# 梯度=膨胀-腐蚀
pie = cv2.imread('img/pie.png')
kernel = np.ones((7,7),np.uint8)
dilate = cv2.dilate(pie,kernel,iterations = 5) # 膨胀
erosion = cv2.erode(pie,kernel,iterations = 5) # 腐蚀
gradient = cv2.morphologyEx(pie, cv2.MORPH_GRADIENT, kernel) # 梯度
res = np.hstack((dilate,erosion,gradient))
cv2.imshow('res', res)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
礼帽与黑帽
礼帽 = 原始输入-开运算结果
cv2.MORPH_TOPHAT
结果:毛刺留下来了
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
img = cv2.imread('img/dige.png')
kernel = np.ones((7,7),np.uint8)
tophat = cv2.morphologyEx(img, cv2.MORPH_TOPHAT, kernel)
cv2.imshow('tophat', tophat)
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
黑帽 = 闭运算-原始输入
迪哥轮廓
cv2.MORPH_BLACKHAT
cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
img = cv2.imread('img/dige.png')
kernel = np.ones((7,7),np.uint8)
blackhat = cv2.morphologyEx(img,cv2.MORPH_BLACKHAT, kernel)
cv2.imshow('blackhat ', blackhat )
cv2.waitKey(0)
cv2.destroyAllWindows()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
图像梯度
Sobel算子
dst = cv2.Sobel(src, ddepth, dx, dy, ksize)
ddepth:图像的深度
dx和dy分别表示水平和竖直方向
ksize是Sobel算子的大小
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
tip:
不建议直接计算x,y,因为这样图像会有重影
import cv2
import numpy as np
def cv_show(img,name):
cv2.imshow(name,img)
cv2.waitKey()
cv2.destroyAllWindows()
img = cv2.imread('img/pie.png',cv2.IMREAD_GRAYSCALE)
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
cv_show(sobelxy,'sobelxy')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
Scharr算子
权值差别更大
laplacian算子
对噪音更敏感
通常和其他一起使用,不单独使用
总结
img = cv2.imread('img/lena.jpg',cv2.IMREAD_GRAYSCALE)
#不同算子的差异
sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=3)
sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=3)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx,0.5,sobely,0.5,0)
scharrx = cv2.Scharr(img,cv2.CV_64F,1,0)
scharry = cv2.Scharr(img,cv2.CV_64F,0,1)
scharrx = cv2.convertScaleAbs(scharrx)
scharry = cv2.convertScaleAbs(scharry)
scharrxy = cv2.addWeighted(scharrx,0.5,scharry,0.5,0)
laplacian = cv2.Laplacian(img,cv2.CV_64F)
laplacian = cv2.convertScaleAbs(laplacian)
res = np.hstack((sobelxy,scharrxy,laplacian))
cv_show(res,'res')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
Canny边缘检测
-
使用高斯滤波器,以平滑图像,滤除噪声。
-
计算图像中每个像素点的梯度强度和方向。
-
应用非极大值(Non-Maximum Suppression)抑制,以消除边缘检测带来的杂散响应。
-
应用双阈值(Double-Threshold)检测来确定真实的和潜在的边缘。
-
通过抑制孤立的弱边缘最终完成边缘检测。
img=cv2.imread("img/car.png",cv2.IMREAD_GRAYSCALE)
v1=cv2.Canny(img,120,250)
v2=cv2.Canny(img,50,100) #更细致
res = np.hstack((v1,v2))
cv_show(res,'res')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
图像金字塔
通过对图像的金字塔变化,抽取若干层进行分析
1.高斯金字塔
放大再缩小,图像会变模糊,因为会有两次损失
向下采样方法(缩小)
img=cv2.imread("AM.png")
down=cv2.pyrDown(img)
cv_show(down,'down')
- 1
- 2
- 3
- 4
- 5
向上采样方法(放大)
up=cv2.pyrUp(img)
cv_show(up,'up')
- 1
- 2
2.拉普拉斯金字塔
第一层结果:原始-(压缩+放大)
down=cv2.pyrDown(img)
down_up=cv2.pyrUp(down)
l_1=img-down_up
cv_show(l_1,'l_1')
- 1
- 2
- 3
- 4
图像轮廓
cv2.findContours(img,mode,method)
-
mode:轮廓检索模式
- RETR_EXTERNAL :只检索最外面的轮廓;
- RETR_LIST:检索所有的轮廓,并将其保存到一条链表当中;
- RETR_CCOMP:检索所有的轮廓,并将他们组织为两层:顶层是各部分的外部边界,第二层是空洞的边界;
- RETR_TREE:检索所有的轮廓,并重构嵌套轮廓的整个层次;
-
method:轮廓逼近方法
- CHAIN_APPROX_NONE:以Freeman链码的方式输出轮廓,所有其他方法输出多边形(顶点的序列)。
- CHAIN_APPROX_SIMPLE:压缩水平的、垂直的和斜的部分,也就是,函数只保留他们的终点部分。
为了更高的准确率,使用二值图像。
img = cv2.imread('img/contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 为了更高的准确率,使用二值图像。
binary, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
#传入绘制图像,轮廓,轮廓索引,颜色模式,线条厚度
# 注意需要copy,要不原图会变。。。
draw_img = img.copy()
res = cv2.drawContours(draw_img, contours, -1, (0, 0, 255), 1)
cv_show(res,'res')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
应用
1.轮廓特征
cnt = contours[0]
#面积
print(cv2.contourArea(cnt))
#周长,True表示闭合的
print(cv2.arcLength(cnt, True))
- 1
- 2
- 3
- 4
- 5
2.轮廓近似
0.1:这个参数越小,近似度越高
epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
img = cv2.imread('img/contours2.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
binary, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[0]
draw_img = img.copy()
res = cv2.drawContours(draw_img, [cnt], -1, (0, 0, 255), 2)
cv_show(res,'res')
# 轮廓近似
epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
draw_img = img.copy()
res = cv2.drawContours(draw_img, [approx], -1, (0, 0, 255), 2)
cv_show(res,'res')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
边界矩形、外接圆
边界矩形
img_rectangle = cv2.rectangle(img.copy(),(x,y),(x+w,y+h)
外接圆
img_radius = cv2.circle(img.copy(),center,radius,(0,255,0),2)
img = cv2.imread('img/contours.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
binary, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cnt = contours[2]
# 外界矩形
x,y,w,h = cv2.boundingRect(cnt)
img_rectangle = cv2.rectangle(img.copy(),(x,y),(x+w,y+h),(0,255,0),2)
cv_show(img_rectangle,'img_rectangle')
# 轮廓面积与边界矩形比
area = cv2.contourArea(cnt) # 轮廓面积
rect_area = w * h # 边界矩形
extent = float(area) / rect_area
print ('轮廓面积与边界矩形比',extent)
# 外接圆
(x,y),radius = cv2.minEnclosingCircle(cnt)
center = (int(x),int(y))
radius = int(radius)
img_radius = cv2.circle(img.copy(),center,radius,(0,255,0),2)
cv_show(img_radius,'img_radius')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
模板匹配
模板匹配和卷积原理很像,模板在原图像上从原点开始滑动,计算模板与(图像被模板覆盖的地方)的差别程度,这个程度的计算方法在OpenCV里有六种,然后将每次计算的结果放入一个矩阵里,作为结果输出。假如原图形是AB大小,而模板是ab大小,则输入结果的矩阵是(A-a+1)*(B-b+1)
- cv2.TM_CCOEFF’,
- ‘cv2.TM_CCOEFF_NORMED’, 计算归一化相关系数,计算出来的值越接近1,越相关
- ‘cv2.TM_CCORR’,
- ‘cv2.TM_CCORR_NORMED’, 计算归一化相关性,计算出来的值越接近1,越相关
- ‘cv2.TM_SQDIFF’,
- cv2.TM_SQDIFF_NORMED’:计算归一化平方不同,计算出来的值越接近0,越相关
res = cv2.matchTemplate(img, template, method)
# 读取原图像
img = cv2.imread('img/lena.jpg', 0)
# 读取模板图像
template = cv2.imread('img/face.jpg', 0)
h, w = template.shape[:2]
methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
for meth in methods:
img2 = img.copy()
# 匹配方法的真值
method = eval(meth)
print(method)
res = cv2.matchTemplate(img, template, method)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
top_left = min_loc
else:
top_left = max_loc
bottom_right = (top_left[0]+w,top_left[1]+h)
#画矩形
cv2.rectangle(img2, top_left, bottom_right, 255 ,2)
plt.subplot(121),plt.imshow(res, cmap='gray')
plt.xticks([]),plt.yticks([]) # 隐藏坐标轴
plt.subplot(122), plt.imshow(img2, cmap='gray')
plt.xticks([]), plt.yticks([]) # 隐藏坐标轴
plt.suptitle(meth)
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
直方图
cv2.calcHist(images,channels,mask,histSize,ranges)
- images: 原图像图像格式为 uint8 或 float32。当传入函数时应 用中括号 [] 括来例如[img]
- channels: 同样用中括号括来它会告函数我们统幅图 像的直方图。
如果入图像是灰度图它的值就是 [0];
如果是彩色图像 的传入的参数可以是 [0][1][2] 它们分别对应着 BGR。 - mask: 掩模图像。统整幅图像的直方图就把它为 None。但是如 果你想统图像某一分的直方图的你就制作一个掩模图像并 使用它。
- histSize:BIN 的数目。也应用中括号括来
- ranges: 像素值范围常为 [0-256]
img = cv2.imread('img/cat.jpg',0) #0表示灰度图
hist = cv2.calcHist([img],[0],None,[256],[0,256])
plt.hist(img.ravel(),256)
plt.show()
- 1
- 2
- 3
- 4
- 5
img = cv2.imread('cat.jpg')
color = ('b','g','r')
for i,col in enumerate(color):
histr = cv2.calcHist([img],[i],None,[256],[0,256])
plt.plot(histr,color = col)
plt.xlim([0,256])
- 1
- 2
- 3
- 4
- 5
- 6
mask操作
# 创建mast
mask = np.zeros(img.shape[:2], np.uint8)
print (mask.shape)
mask[100:300, 100:400] = 255
cv_show(mask,'mask')
img = cv2.imread('cat.jpg', 0)
cv_show(img,'img')
masked_img = cv2.bitwise_and(img, img, mask=mask)#与操作
cv_show(masked_img,'masked_img')
hist_full = cv2.calcHist([img], [0], None, [256], [0, 256])
hist_mask = cv2.calcHist([img], [0], mask, [256], [0, 256])
plt.subplot(221), plt.imshow(img, 'gray')
plt.subplot(222), plt.imshow(mask, 'gray')
plt.subplot(223), plt.imshow(masked_img, 'gray')
plt.subplot(224), plt.plot(hist_full), plt.plot(hist_mask)
plt.xlim([0, 256])
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
直方图均衡化
equ = cv2.equalizeHist(img)
plt.hist(equ.ravel(),256)
自定义直方图均衡化
可能会产生局部噪音
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
res_clahe = clahe.apply(img)
均衡化总结
img = cv2.imread('img/clahe.jpg',0) #0表示灰度图 #clahe
plt.hist(img.ravel(),256);
plt.show()
# 均衡化
equ = cv2.equalizeHist(img)
plt.hist(equ.ravel(),256)
plt.show()
# 自定义均衡化
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
res_clahe = clahe.apply(img)
res = np.hstack((img,equ,res_clahe))
cv_show(res,'res')
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
傅里叶变换
我们生活在时间的世界中,早上7:00起来吃早饭,8:00去挤地铁,9:00开始上班。。。以时间为参照就是时域分析。
但是在频域中一切都是静止的!
https://zhuanlan.zhihu.com/p/19763358
傅里叶变换的作用
-
高频:变化剧烈的灰度分量,例如边界
-
低频:变化缓慢的灰度分量,例如一片大海
滤波
-
低通滤波器:只保留低频,会使得图像模糊
-
高通滤波器:只保留高频,会使得图像细节增强
opencv中主要就是cv2.dft()和cv2.idft(),输入图像需要先转换成np.float32 格式,得到的结果中频率为0的部分会在左上角,通常要转换到中心位置,通过shift变换
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('lena.jpg',0)
img_float32 = np.float32(img)
dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
magnitude_spectrum = 20*np.log(cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1]))
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(magnitude_spectrum, cmap = 'gray')
plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
低通滤波
import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('lena.jpg',0)
img_float32 = np.float32(img)
dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
rows, cols = img.shape
crow, ccol = int(rows/2) , int(cols/2) # 中心位置
# 低通滤波
mask = np.zeros((rows, cols, 2), np.uint8)
mask[crow-30:crow+30, ccol-30:ccol+30] = 1
# IDFT
fshift = dft_shift*mask
f_ishift = np.fft.ifftshift(fshift)
img_back = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img_back, cmap = 'gray')
plt.title('Result'), plt.xticks([]), plt.yticks([])
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
高通滤波
img = cv2.imread('lena.jpg',0)
img_float32 = np.float32(img)
dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
dft_shift = np.fft.fftshift(dft)
rows, cols = img.shape
crow, ccol = int(rows/2) , int(cols/2) # 中心位置
# 高通滤波
mask = np.ones((rows, cols, 2), np.uint8)
mask[crow-30:crow+30, ccol-30:ccol+30] = 0
# IDFT
fshift = dft_shift*mask
f_ishift = np.fft.ifftshift(fshift)
img_back = cv2.idft(f_ishift)
img_back = cv2.magnitude(img_back[:,:,0],img_back[:,:,1])
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(img_back, cmap = 'gray')
plt.title('Result'), plt.xticks([]), plt.yticks([])
plt.show()
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26