python均值滤波函数 均值滤波器函数

OpenCV-Python系列六:图像滤波

图像滤波是一种十分常见的图像处理手段。通常,你可以认为相邻位置像素是紧密联系的,它们共同来显示对某个物体,图像滤波则通过运算来排除图像中和周围相差大的像素。当然,这并不是绝对的, 有时候你为了评估图像的质量,也会将这些“特立独行”的像素作为选取的目标 。无论你采用什么方法,记住你要的目标就行,有时候你的目标可能是别人的背景。

成都创新互联从2013年开始,是专业互联网技术服务公司,拥有项目成都网站制作、网站建设、外贸网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元封丘做网站,已为上家服务,为封丘各地企业和个人服务,联系电话:18980820575

滤波常常会使得图像变得模糊(非绝对),那么,为什么你需要将一幅清晰的图像变得模糊呢?下面的例子应该可以解释。

高斯滤波采用满足正态分布的核模板,其参数的主要参数是标准差σ,代表核的离散程度,σ值越小,模板中心系数与边缘系数差越大,平滑的程度越小。

高斯滤波对图像采集过程中由于不良照明/高温引起的传感器噪声信号有较好的效果,消除了图像中的高频信号。

由于得到的是一维的Gaussian Kernel,你可以采用下面的方式转为二维的

为了便于直观感受高斯滤波的效果,使用Canny算子来提取轮廓对比,你可以试试在特征提取前加高斯滤波对比。

补充说明:对于均值滤波,你也可以使用cv2.boxFilter(src, ddepth, ksize[, dst[, anchor[, normalize[, borderType]]]])来实现,需要将normalize设置为True,当设置normalize为False时,实现的是将kernel内像素相加,官方文档做出的描述为:

中值滤波对图像中的脉冲型(椒盐等)噪声信号处理效果好,当 你的应用场景存在这种颗粒感的噪声信号时,中值滤波会是一种很好的选择 。它,选取kernel区域内像素点集的中值最为锚点的像素值,对类似投票机制中的最高分(高灰阶点)和最低分(过低灰阶点)影响有很好的抑制作用。

如果你的应用涉及到图像美化,双边滤波可以初步达到你的期望,关于双边滤波,这里不做展开,由你来探索,其函数参数信息如下。

对于opencv-python的图像滤波部分有问题欢迎留言, Have Fun With OpenCV-Python, 下期见。

数字图像处理Python实现图像灰度变换、直方图均衡、均值滤波

import CV2

import copy

import numpy as np

import random

使用的是pycharm

因为最近看了《银翼杀手2049》,里面Joi实在是太好看了所以原图像就用Joi了

要求是灰度图像,所以第一步先把图像转化成灰度图像

# 读入原始图像

img = CV2.imread('joi.jpg')

# 灰度化处理

gray = CV2.cvtColor(img, CV2.COLOR_BGR2GRAY)

CV2.imwrite('img.png', gray)

第一个任务是利用分段函数增强灰度对比,我自己随便写了个函数大致是这样的

def chng(a):

if a 255/3:

b = a/2

elif a 255/3*2:

b = (a-255/3)*2 + 255/6

else:

b = (a-255/3*2)/2 + 255/6 +255/3*2

return b

rows = img.shape[0]

cols = img.shape[1]

cover = copy.deepcopy(gray)

for i in range(rows):

for j in range(cols):

cover[i][j] = chng(cover[i][j])

CV2.imwrite('cover.png', cover)

下一步是直方图均衡化

# histogram equalization

def hist_equal(img, z_max=255):

H, W = img.shape

# S is the total of pixels

S = H * W * 1.

out = img.copy()

sum_h = 0.

for i in range(1, 255):

ind = np.where(img == i)

sum_h += len(img[ind])

z_prime = z_max / S * sum_h

out[ind] = z_prime

out = out.astype(np.uint8)

return out

covereq = hist_equal(cover)

CV2.imwrite('covereq.png', covereq)

在实现滤波之前先添加高斯噪声和椒盐噪声(代码来源于网络)

不知道这个椒盐噪声的名字是谁起的感觉隔壁小孩都馋哭了

用到了random.gauss()

percentage是噪声占比

def GaussianNoise(src,means,sigma,percetage):

NoiseImg=src

NoiseNum=int(percetage*src.shape[0]*src.shape[1])

for i in range(NoiseNum):

randX=random.randint(0,src.shape[0]-1)

randY=random.randint(0,src.shape[1]-1)

NoiseImg[randX, randY]=NoiseImg[randX,randY]+random.gauss(means,sigma)

if NoiseImg[randX, randY] 0:

NoiseImg[randX, randY]=0

elif NoiseImg[randX, randY]255:

NoiseImg[randX, randY]=255

return NoiseImg

def PepperandSalt(src,percetage):

NoiseImg=src

NoiseNum=int(percetage*src.shape[0]*src.shape[1])

for i in range(NoiseNum):

randX=random.randint(0,src.shape[0]-1)

randY=random.randint(0,src.shape[1]-1)

if random.randint(0,1)=0.5:

NoiseImg[randX,randY]=0

else:

NoiseImg[randX,randY]=255

return NoiseImg

covereqg = GaussianNoise(covereq, 2, 4, 0.8)

CV2.imwrite('covereqg.png', covereqg)

covereqps = PepperandSalt(covereq, 0.05)

CV2.imwrite('covereqps.png', covereqps)

下面开始均值滤波和中值滤波了

就以n x n为例,均值滤波就是用这n x n个像素点灰度值的平均值代替中心点,而中值就是中位数代替中心点,边界点周围补0;前两个函数的作用是算出这个点的灰度值,后两个是对整张图片进行

#均值滤波模板

def mean_filter(x, y, step, img):

sum_s = 0

for k in range(x-int(step/2), x+int(step/2)+1):

for m in range(y-int(step/2), y+int(step/2)+1):

if k-int(step/2) 0 or k+int(step/2)+1 img.shape[0]

or m-int(step/2) 0 or m+int(step/2)+1 img.shape[1]:

sum_s += 0

else:

sum_s += img[k][m] / (step*step)

return sum_s

#中值滤波模板

def median_filter(x, y, step, img):

sum_s=[]

for k in range(x-int(step/2), x+int(step/2)+1):

for m in range(y-int(step/2), y+int(step/2)+1):

if k-int(step/2) 0 or k+int(step/2)+1 img.shape[0]

or m-int(step/2) 0 or m+int(step/2)+1 img.shape[1]:

sum_s.append(0)

else:

sum_s.append(img[k][m])

sum_s.sort()

return sum_s[(int(step*step/2)+1)]

def median_filter_go(img, n):

img1 = copy.deepcopy(img)

for i in range(img.shape[0]):

for j in range(img.shape[1]):

img1[i][j] = median_filter(i, j, n, img)

return img1

def mean_filter_go(img, n):

img1 = copy.deepcopy(img)

for i in range(img.shape[0]):

for j in range(img.shape[1]):

img1[i][j] = mean_filter(i, j, n, img)

return img1

完整main代码如下:

if __name__ == "__main__":

# 读入原始图像

img = CV2.imread('joi.jpg')

# 灰度化处理

gray = CV2.cvtColor(img, CV2.COLOR_BGR2GRAY)

CV2.imwrite('img.png', gray)

rows = img.shape[0]

cols = img.shape[1]

cover = copy.deepcopy(gray)

for i in range(rows):

for j in range(cols):

cover[i][j] = chng(cover[i][j])

CV2.imwrite('cover.png', cover)

covereq = hist_equal(cover)

CV2.imwrite('covereq.png', covereq)

covereqg = GaussianNoise(covereq, 2, 4, 0.8)

CV2.imwrite('covereqg.png', covereqg)

covereqps = PepperandSalt(covereq, 0.05)

CV2.imwrite('covereqps.png', covereqps)

meanimg3 = mean_filter_go(covereqps, 3)

CV2.imwrite('medimg3.png', meanimg3)

meanimg5 = mean_filter_go(covereqps, 5)

CV2.imwrite('meanimg5.png', meanimg5)

meanimg7 = mean_filter_go(covereqps, 7)

CV2.imwrite('meanimg7.png', meanimg7)

medimg3 = median_filter_go(covereqg, 3)

CV2.imwrite('medimg3.png', medimg3)

medimg5 = median_filter_go(covereqg, 5)

CV2.imwrite('medimg5.png', medimg5)

medimg7 = median_filter_go(covereqg, 7)

CV2.imwrite('medimg7.png', medimg7)

medimg4 = median_filter_go(covereqps, 7)

CV2.imwrite('medimg4.png', medimg4)

均值滤波

  均值滤波是指用当前像素点周围N·N个像素值的均值来代替当前像素值。使用该方法遍历处理图像内的每一个像素点,即可完成整幅图像的均值滤波。

例如,希望对图7-7中位于第5行第5列的像素点进行均值滤波。

根据上述运算,针对每一个像素点,都是与一个内部值均为1/25的5×5矩阵相乘,得到均值滤波的计算结果,如图7-11所示。

将使用的5×5矩阵一般化,可以得到如图7-12所示的结果。

式中,M和N分别对应高度和宽度。一般情况下,M和N是相等的,例如比较常用的3×3、5×5、7×7等。如果M和N的值越大,参与运算的像素点数量就越多,图像失真越严重。

在OpenCV中,实现均值滤波的函数是cv2.blur(),其语法格式为:

式中:

通常情况下,使用均值滤波函数时,对于锚点anchor和边界样式borderType,直接采用其默认值即可。

【例7.2】针对噪声图像,使用不同大小的卷积核对其进行均值滤波,并显示均值滤波的情况。

  从图中可以看出,使用5×5的卷积核进行滤波处理时,图像的失真不明显;而使用30×30的卷积核进行滤波处理时,图像的失真情况较明显。

  卷积核越大,参与到均值运算中的像素就会越多,即当前点计算的是更多点的像素值的平均值。因此,卷积核越大,去噪效果越好,当然花费的计算时间也会越长,同时让图像失真越严重。在实际处理中,要在失真和去噪效果之间取得平衡,选取合适大小的卷积核。

中值滤波

一. 中值滤波:

中值滤波器是一种可以使图像平滑的滤波器。它使用滤波器范围内的像素的中值去代表该范围内所有的像素。中值滤波是消除图像噪声最常见的手段之一,特别是消除椒盐噪声,中值滤波的效果要比均值滤波更好。

二. python实现中值滤波和均值滤波,并用两种滤波器对受到椒盐噪声污染的图像进行去噪

import cv2

import numpy as np

# Median filter

def median_filter(img, K_size=3):

H, W, C = img.shape

## Zero padding

pad = K_size // 2

out = np.zeros((H + pad*2, W + pad*2, C), dtype=np.float)

out[pad:pad+H, pad:pad+W] = img.copy().astype(np.float)

tmp = out.copy()

# filtering

for y in range(H):

    for x in range(W):

        for c in range(C):

            out[pad+y, pad+x, c] = np.median(tmp[y:y+K_size, x:x+K_size, c])

out = out[pad:pad+H, pad:pad+W].astype(np.uint8)

return out

# Average filter

def average_filter(img, G=3):

out = img.copy()

H, W, C = img.shape

Nh = int(H / G)

Nw = int(W / G)

for y in range(Nh):

    for x in range(Nw):

        for c in range(C):

            out[G*y:G*(y+1), G*x:G*(x+1), c] = np.mean(out[G*y:G*(y+1), G*x:G*(x+1), c]).astype(np.int)

return out

# Read image

img = cv2.imread("../paojie_sp.jpg")

# Median Filter and Average Filter

out1 = median_filter(img, K_size=3)

out2 = average_filter(img,G=3)

# Save result

cv2.imwrite("out1.jpg", out1)

cv2.imwrite("out2.jpg", out2)

cv2.waitKey(0)

cv2.destroyAllWindows()

三. 实验结果

可以明显看出,对于受到椒盐噪声污染的图像,中值滤波往往比均值滤波的去噪效果要好!

四. 参考内容:

   

【转载】Python实现信号滤波(基于scipy)

利用Python scipy.signal.filtfilt() 实现信号滤波

Required input defintions are as follows;

time: Time between samples

band: The bandwidth around the centerline freqency that you wish to filter

freq: The centerline frequency to be filtered

ripple: The maximum passband ripple that is allowed in db

order: The filter order. For FIR notch filters this is best set to 2 or 3, IIR filters are best suited for high values of order. This algorithm is hard coded to FIR filters

filter_type: 'butter', 'bessel', 'cheby1', 'cheby2', 'ellip'

data: the data to be filtered

用python设计FIR陷波滤波器


本文标题:python均值滤波函数 均值滤波器函数
文章地址:http://pwwzsj.com/article/hgiidi.html