高斯均值滤波源码实现
高斯滤波
- 原理
- 当前像素点与滤波盒相乘,滤波盒越中间数越大
- 不同滤波方法只是滤波盒不同
# 高斯API 原图有问题有噪声小点
import cv2
import numpy as np
img = cv2.imread('image11.jpg',1)
cv2.imshow('src',img)
dst = cv2.GaussianBlur(img,(5,5),1.5)
cv2.imshow('dst',dst)
cv2.waitKey(0)
- 结果 缺点模糊
均值滤波
#均值滤波源码实现 6*6 1 。 * 【6*6】/36 = mean -》P
import cv2
import numpy as np
img = cv2.imread('image11.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
dst = np.zeros((height,width,3),np.uint8)
for i in range(3,height-3):
for j in range(3,width-3):
sum_b = int(0)
sum_g = int(0)
sum_r = int(0)
for m in range(-3,3):#-3 -2 -1 0 1 2
for n in range(-3,3):
(b,g,r) = img[i+m,j+n]
sum_b = sum_b+int(b)
sum_g = sum_g+int(g)
sum_r = sum_r+int(r)
b = np.uint8(sum_b/36)
g = np.uint8(sum_g/36)
r = np.uint8(sum_r/36)
dst[i,j] = (b,g,r)
cv2.imshow('dst',dst)
cv2.waitKey(0)
中值滤波
# 中值滤波 3*3 像素排序,选取中间的值替换原来的像素值
import cv2
import numpy as np
img = cv2.imread('image11.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
# 简化代码 灰度处理
img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)
cv2.imshow('src',img)
dst = np.zeros((height,width,3),np.uint8)
# 九个元素 排序
collect = np.zeros(9,np.uint8)
# 防止数据越界
for i in range(1,height-1):
for j in range(1,width-1):
k = 0
for m in range(-1,2):
for n in range(-1,2):
# 当前灰度值
gray = img[i+m,j+n]
# 所有数据放入collect
collect[k] = gray
k = k+1
# 0 1 2 3 4 5 6 7 8
# 1
# 9个元素排序 选择排序
for k in range(0,9):
p1 = collect[k]
for t in range(k+1,9):
if p1<collect[t]:
# 交换
mid = collect[t]
collect[t] = p1
p1 = mid
# 生成新的元素
dst[i,j] = collect[4]
cv2.imshow('dst',dst)
cv2.waitKey(0)
- 结果 效果不是那么明显
生成新的元素
dst[i,j] = collect[4]
cv2.imshow(‘dst’,dst)
cv2.waitKey(0)
- 结果 效果不是那么明显