OpenCV—模糊处理与高斯模糊

均值模糊与中值模糊

import cv2 as cv
import numpy as np


def blur_demo(img):
    dst1 = cv.blur(img, (5, 5))  # 均值模糊
    cv.imshow("blur_demo", dst1)


def median_blur_demo(img):
    dst2 = cv.medianBlur(img, 9)  # 中值模糊  有去椒盐的功能(去燥)
    cv.imshow("medianBlur_demo", dst2)

中值滤波处理椒盐噪声效果显著

自定义模糊

注意要做防止溢出处理

def custom_demo(img):
    kernel = np.ones([5, 5], np.float32)/25
    dst3 = cv.filter2D(img, -1, kernel=kernel)  # 自定义模糊
    cv.imshow("custom_demo", dst3)

 自定义锐化操作:

def custom_demo(img):
    # kernel = np.ones([5, 5], np.float32)/25
    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], np.float32)/9
    dst3 = cv.filter2D(img, -1, kernel=kernel)  # 自定义模糊
    cv.imshow("custom_demo", dst3)

 高斯模糊

# 将范围定义在0-255之间
def clamp(pv):
    if pv > 255:
        return 255
    elif pv < 0:
        return 0
    else:return pv


# 定义高斯噪声函数
def gaussian_demo(img):  #高斯模糊
    h, w, c = img.shape
    for row in range(0, h, 1):
        for col in  range(0, w, 1):
            s = np.random.normal(0, 20, 3)
            b = img[row, col, 0]  # blue
            g = img[row, col, 1]  # green
            r = img[row, col, 2]  # red
            img[row, col, 0] = clamp(b + s[0])
            img[row, col, 1] = clamp(g + s[1])
            img[row, col, 2] = clamp(r + s[2])
    cv.imshow("gaussian_demo", img)

测试程序 

import cv2 as cv
import numpy as np


def blur_demo(img):
    dst1 = cv.blur(img, (5, 5))  # 均值模糊
    cv.imshow("blur_demo", dst1)


def median_blur_demo(img):
    dst2 = cv.medianBlur(img, 9)  # 中值模糊  有去椒盐的功能(去燥)
    cv.imshow("medianBlur_demo", dst2)


def custom_demo(img):
    # kernel = np.ones([5, 5], np.float32)/25
    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], np.float32)/9
    dst3 = cv.filter2D(img, -1, kernel=kernel)  # 自定义模糊
    cv.imshow("custom_demo", dst3)


# 将范围定义在0-255之间
def clamp(pv):
    if pv > 255:
        return 255
    elif pv < 0:
        return 0
    else:return pv


# 定义高斯噪声函数
def gaussian_demo(img):  #高斯模糊
    h, w, c = img.shape
    for row in range(0, h, 1):
        for col in  range(0, w, 1):
            s = np.random.normal(0, 20, 3)
            b = img[row, col, 0]  # blue
            g = img[row, col, 1]  # green
            r = img[row, col, 2]  # red
            img[row, col, 0] = clamp(b + s[0])
            img[row, col, 1] = clamp(g + s[1])
            img[row, col, 2] = clamp(r + s[2])
    cv.imshow("gaussian_demo", img)

src1 = cv.imread("D:/JetBrains/PyCharm 2019.1.3/PycharmProjects/Study/opencv_study/Penguins.jpg")  # 读取图像
src2 = cv.imread("D:/JetBrains/PyCharm 2019.1.3/PycharmProjects/Study/opencv_study/s.jpg")
cv.namedWindow("input img", cv.WINDOW_AUTOSIZE)


cv.imshow("input img", src1)
blur_demo(src1)
cv.imshow("input img2", src2)
median_blur_demo(src2)
custom_demo(src1)
gaussian_demo(src1)
dst = cv.GaussianBlur(src1, (0, 0), 5)  # 高斯模糊的另外一种方法
cv.imshow("GaussianBlur", dst)

cv.waitKey(0)
cv.destroyAllWindows()

结果图: 

 

 

你可能感兴趣的:(OpenCV,Python)