亲宝软件园·资讯

展开

opencv python均值滤波 opencv+python实现均值滤波

油醋三椒 人气:1

原理

均值滤波其实就是对目标像素及周边像素取平均值后再填回目标像素来实现滤波目的的方法,当滤波核的大小是3×3 3\times 33×3时,则取其自身和周围8个像素值的均值来代替当前像素值。
均值滤波也可以看成滤波核的值均为 1 的滤波。
优点:算法简单,计算速度快;
缺点:降低噪声的同时使图像产生模糊,特别是景物的边缘和细节部分。

代码

import cv2 as cv
import numpy as np
import math
import copy

def spilt( a ):
 if a/2 == 0:
  x1 = x2 = a/2
 else:
  x1 = math.floor( a/2 )
  x2 = a - x1
 return -x1,x2

def original (i, j, k,a, b,img):
 x1, x2 = spilt(a)
 y1, y2 = spilt(b)
 temp = np.zeros(a * b)
 count = 0
 for m in range(x1, x2):
  for n in range(y1, y2):
   if i + m < 0 or i + m > img.shape[0] - 1 or j + n < 0 or j + n > img.shape[1] - 1:
    temp[count] = img[i, j, k]
   else:
    temp[count] = img[i + m, j + n, k]
   count += 1
 return temp

def average_function(a , b ,img):
 img0 = copy.copy(img)
 for i in range (0 , img.shape[0] ):
  for j in range (2 ,img.shape[1] ):
   for k in range (img.shape[2]):
    temp = original(i, j, k, a, b, img0)
    img[i,j,k] = int ( np.mean(temp))
 return img 
 
def main():
 img0 = cv.imread(r"noise.jpg")

 ave_img = average_function( 3 , 3, copy.copy(img0) ) #(3,3)滤波器大小 

 cv.imshow("ave_img",ave_img) 
 cv.imshow("original",img0)

 cv.waitKey(0)
 cv.destroyAllWindows()

if __name__ == "__main__":
 main()

样例

原图:

滤波核为3×3 3\times 33×3的均值滤波后:

加载全部内容

相关教程
猜你喜欢
用户评论