OpenCV—python Max-Mix filter 最大-最小滤波器

一、Max-Min Filter 算法原理

图像的细节属于低频信息,图像的边缘属于高频信息。我们使用一定大小的 Max-Min 滤波器作用于图像,当滤波器作用于图像细节时,输出结果往往趋向于0(黑色);而滤波器作用于图像边缘时,Max-Min 输出结果往往趋向于255(白色)。所以 最大-最小滤波器 能有效地用于检测图像的边缘和轮廓。

MAX-MIN滤波器使用网格内像素的最大值和最小值的差值对网格内像素重新赋值。通常用于边缘检测。
边缘检测用于检测图像中的线。像这样提取图像中的信息的操作被称为特征提取。边缘检测通常在灰度图像上进行。

滤波流程图:
在这里插入图片描述

二、代码实现:

import cv2
import numpy as np



def max_min_filter(img, K_size):
    height, width = img.shape
    pad = K_size // 2
    out_img = img.copy()
    pad_img = np.zeros((height + pad*2, width + pad*2), dtype=np.uint8)
    pad_img[pad: pad+height, pad: pad+width] = img.copy()

    for y in range(height):
        for x in range(width):
            out_img[y,x] = np.max(pad_img[y:y+K_size, x:x+K_size]) - np.min(pad_img[y:y+K_size, x:x+K_size])
    return out_img



if __name__ == '__main__':
    gray = cv2.imread("./Test_image2.jpg", 0)
    out_0 = max_min_filter(gray, 3)
    out_1 = cv2.bitwise_not(out_0)

    cv2.imwrite("out_0.png", out_0)
    cv2.imwrite("out_1.png", out_1)

在这里插入图片描述
示例:阴影去除

import time
import cv2
import numpy as np
import matplotlib.pyplot as plt


def max_filtering(height,width,ksize, I_temp):
    n = (ksize//2)
    wall = np.zeros((height+n*2, width+n*2),dtype=np.int32)
    temp = wall.copy()
    wall[n:height+n, n:width+n] = I_temp.copy()

    for y in range(height):
        for x in range(width):
            temp[y+n,x+n] = np.max(wall[y:y+ksize,x:x+ksize])
    return temp[n:height+n, n:width+n]


def min_filtering(height,width,ksize, A):
    n = (ksize // 2)
    wall_min = np.full((height+n*2, width+n*2), 255,dtype=np.int32)
    temp_min = wall_min.copy()
    wall_min[n:height+n, n:width+n] = A.copy()

    for y in range(height):
        for x in range(width):
            temp_min[y+n,x+n] = np.min(wall_min[y:y+ksize,x:x+ksize])
    return temp_min[n:height+n, n:width+n]


def background_subtraction(I, B):
    O = I - B
    norm_img = cv2.normalize(O, None, 0,255, norm_type=cv2.NORM_MINMAX)
    return norm_img


def min_max_filtering(M, ksize, I):
    height,width = I.shape[:2]
    if M == 0:
        A = max_filtering(height,width,ksize, I)
        B = min_filtering(height,width,ksize, A)
        normalised_img = background_subtraction(I, B)
    elif M == 1:
        A = min_filtering(height,width,ksize, I)
        B = max_filtering(height,width,ksize, A)
        normalised_img = background_subtraction(I, B)
    else:
        normalised_img = None
    return normalised_img


if __name__ == '__main__':
    Image = cv2.imread('Test_image3.jpg',0)

    t0 = time.time()
    output1 = min_max_filtering(0, 21, Image)
    t1 = time.time()
    
    print("Total cost time is:",t1-t0)
    cv2.imwrite("Test_image3_out.png",output1)

效果图有点不干净
在这里插入图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页