数字图像处理 | python实现线性滤波和非线性滤波

数字图像处理 | python实现线性滤波和非线性滤波

python实现线性滤波和非线性滤波



前言

这是数字图像处理课程上的作业,内容是使用非线性滤波和线性滤波处理一张图片。里面内容包含理论和代码。/font>


一、线性滤波是什么?

图像的空域线性滤波和非线性滤波在空域对图像进行滤波处理无非两种情况,线性滤波和非线性滤波。滤波的意思就是对原图像的每个像素周围一定范围内的像素进行运算,运算的范围就称为掩膜或领域。而运算就分两种了,如果运算只是对各像素灰度值进行简单处理(如乘一个权值)最后求和,就称为线性滤波;
原始图片像素
原始图片像素
在这里插入图片描述
卷积核

二、非线性滤波是什么?

而如果对像素灰度值的运算比较复杂,而不是最后求和的简单运算,则是非线性滤波;如求一个像素周围3x3范围内最大值、最小值、中值、均值等操作都不是简单的加权,都属于非线性滤波。

三、python代码实现

1.python实现

代码如下(示例):

import cv2 as cv
import numpy as np

convolution_kernel = np.array([
    [-1, 0, 1],
    [-2, 0, 2],
    [-1, 0, 1]
])


def linear_conv(input_image, input_conv):
    height = input_image.shape[0]
    width = input_image.shape[1]
    channels = input_image.shape[2]
    conv_height = input_conv.shape[0]
    matrix = np.zeros([height + 2, width + 2, channels], np.uint8)
    matrix[1:height+1, 1:width+1, :] = input_image
    new_image = []
    for cow in range(height):
        for col in range(width):
            for channel in range(channels):
                new_image.append(
                    np.sum(np.multiply(input_conv, matrix[cow:cow + conv_height, col:col + conv_height,  channel])))
    new_image = np.array(new_image).reshape([height, width, channels])/255.0
    cv.imshow("linear_conv_result", new_image)


def nonlinear_conv(input_image, shape):
    height = input_image.shape[0]
    width = input_image.shape[1]
    channels = input_image.shape[2]
    matrix = np.zeros([height + 2, width + 2, channels], np.uint8)
    matrix[1:height+1, 1:width+1, :] = input_image
    new_image = []
    for cow in range(height):
        for col in range(width):
            for channel in range(channels):
                new_image.append(np.max(matrix[cow:cow + shape, col:col + shape, channel]))
    new_image = np.array(new_image).reshape([height, width, channels])
    cv.imshow("nonlinear_conv_result", new_image)


# 取图片
src = cv.imread("1.jfif")   # blue,green,red
# 窗口
cv.namedWindow("input image", cv.WINDOW_AUTOSIZE)
# 展示
cv.imshow("input image", src)
# 线性
linear_conv(src, convolution_kernel)
# 非线性
nonlinear_conv(src, 3)
# 暂停
cv.waitKey(0)
cv.destroyAllWindows()

运行结果

在这里插入图片描述


总结

在这里插入图片描述
如果有帮助的话,欢迎关注本人公众号。会更新自然语言处理的内容哦



版权声明:本文为qq_35764460原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。