Max-Min Filter 實現及用於檢測圖像邊緣


一. 邊緣檢測

        邊緣檢測通常作用於灰度圖像上。邊緣檢測用於檢測圖像中的線。


邊緣檢測結果 ↑

二. 最大 - 最小濾波器(Max - Min)


3*3 Max-Min Filter 算法原理 ↑

        我們知道,圖像的細節屬於低頻信息,圖像的邊緣屬於高頻信息。我們使用一定大小的 Max-Min 濾波器作用於圖像,當濾波器作用於圖像細節時,輸出結果往往趨向於0(黑色);而濾波器作用於圖像邊緣時,Max-Min 輸出結果往往趨向於255(白色)。所以 最大-最小濾波器 能有效地用於檢測圖像的邊緣和輪廓。


三. python實現 最大-最小 濾波器

用3*3的 Max-Min 濾波器對圖像進行邊緣檢測

import cv2

import numpy as np

# BGR to Gray scale

def BGR2GRAY(img):

    b = img[:, :, 0].copy()

    g = img[:, :, 1].copy()

    r = img[:, :, 2].copy()

    # Gray scale

    out = 0.2126 * r + 0.7152 * g + 0.0722 * b

    out = out.astype(np.uint8)

    return out

# max-min filter

def max_min_filter(img, K_size=3):

    H, W = img.shape

    # Zero padding

    pad = K_size // 2

    out = np.zeros((H + pad * 2, W + pad * 2), dtype=np.float)

    out[pad: pad + H, pad: pad + W] = gray.copy().astype(np.float)

    tmp = out.copy()

    # filtering

    for y in range(H):

        for x in range(W):

        # core code

            out[pad + y, pad + x] = np.max(tmp[y: y + K_size, x: x + K_size]) - \

                np.min(tmp[y: y + K_size, x: x + K_size])

    out = out[pad: pad + H, pad: pad + W].astype(np.uint8)

    return out

# Read image

img = cv2.imread("../paojie.jpg").astype(np.float)

# get grayscale

gray = BGR2GRAY(img)

# Max-Min filtering

out = max_min_filter(gray, K_size=3)

# Save result

cv2.imwrite("out.jpg", out)

cv2.imshow("result", out)

cv2.waitKey(0)

cv2.destroyAllWindows()

 


四. 實驗結果:


邊緣檢測結果 ↑
 

原圖 ↑

五. 參考內容:

  https://www.jianshu.com/p/fea3b4d741ab


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM