Python OpenCV _4初级滤波(均值滤波,高斯滤波,中值滤波)

此系列源码在我的GitHub里:https://github.com/yeyujujishou19/Python-OpenCV

理论就不说了,直接上代码和效果图

原图

Python OpenCV _4初级滤波(均值滤波,高斯滤波,中值滤波)_第1张图片

一,均值滤波

代码:

# coding=utf-8
import cv2

img = cv2.imread("D:/lena.jpg", 0)
result = cv2.blur(img, (5, 5))

cv2.imshow("Origin", img)
cv2.imshow("Blur", result)

cv2.waitKey(0)
cv2.destroyAllWindows()

代码结果:

Python OpenCV _4初级滤波(均值滤波,高斯滤波,中值滤波)_第2张图片

二,高斯滤波

代码:

# coding=utf-8
import cv2

img = cv2.imread("D:/lena.jpg", 0)
gaussianResult = cv2.GaussianBlur(img,(5,5),1.5)

cv2.imshow("Origin", img)
cv2.imshow("GaussianBlur", gaussianResult)

cv2.waitKey(0)
cv2.destroyAllWindows()

代码结果:

Python OpenCV _4初级滤波(均值滤波,高斯滤波,中值滤波)_第3张图片

 

三,中值滤波

代码:

# coding=utf-8
import cv2
import numpy as np

#加入椒盐噪声
def salt(img, n):
    for k in range(n):
        i = int(np.random.random() * img.shape[1]);
        j = int(np.random.random() * img.shape[0]);
        if img.ndim == 2:
            img[j, i] = 255
        elif img.ndim == 3:
            img[j, i, 0] = 255
            img[j, i, 1] = 255
            img[j, i, 2] = 255
    return img


img = cv2.imread("D:/lena.jpg", 0)
result = salt(img, 500) #加入椒盐噪声
median = cv2.medianBlur(result, 5)

cv2.imshow("Salt", result)
cv2.imshow("Median", median)

cv2.waitKey(0)

代码结果:

Python OpenCV _4初级滤波(均值滤波,高斯滤波,中值滤波)_第4张图片

 

欢迎扫码关注我的微信公众号

你可能感兴趣的:(#,OpenCV系列笔记)