中值滤波

2021-12-12  本文已影响0人  奇点创客
// MedianFilter.cpp
#include <iostream>   // for std::cout, std::endl
#include <utility>    // for std::pair
#include <vector>     // for std::vector
#include <format>     // for std::format(C++20)
#include <algorithm>  // for std::ranges::for_each, sort(C++20)

using std::cout, std::endl;
using Matrix = std::vector<std::vector<int>>;
using Position = std::pair<size_t, size_t>;

int MedianValueForUnit(const Matrix& m, const Position& p)
{
    using std::ranges::sort;

    std::vector<int> temp;
    const auto& [row, col] = p;
    for (int r = 0; r < 3; r++)
        for (int c = 0; c < 3; c++)
            temp.push_back(m[row + r][col + c]);
    sort(temp);
    return temp[4];
}

Matrix MedianFilter(const Matrix& m)
{
    using std::ranges::for_each;

    const auto row{ m.size() - 2 };
    const auto col{ m[0].size() - 2 };
    Matrix re(row);
    for_each(re, [col](auto& row) { row.resize(col); });

    for (int r = 0; r < row; r++)
        for (int c = 0; c < col; c++)
            re[r][c] = MedianValueForUnit(m, Position(r, c));
    return re;
}

std::ostream& operator<<(std::ostream& os, const Matrix& m)
{
    for (const auto& v : m) {
        cout << "[";
        for (const auto& i : v)
            cout << std::format("{:>2} ", i);
        cout << "]\n";
    }
    return os;
}

int main()
{
    Matrix m0{
        {1,  2,  3, 4},
        {5, 12,  7, 8},
        {9, 10, 11, 3},
        {4,  3,  1, 2} };

    cout << m0 << endl;
    cout << MedianFilter(m0) << endl;

    Matrix m1{
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5},
        {1, 2, 3, 4, 5} };

    cout << m1 << endl;
    cout << MedianFilter(m1) << endl;
}
# MedianFilter.py

Matrix = list[list[int]]
Position = tuple[int, int]


def median_value_for_unit(m: Matrix, p: Position) -> int:
    temp = []
    row, col = p
    for r in range(3):
        for c in range(3):
            temp.append(m[row + r][col + c])
    temp.sort()
    return temp[4]


def median_filter(m: Matrix) -> Matrix:
    row = len(m) - 2
    col = len(m[0]) - 2
    re = [[0 for _ in range(row)] for _ in range(col)]

    for r in range(row):
        for c in range(col):
            re[r][c] = median_value_for_unit(m, (r, c))
    return re


def print_matrix(m: Matrix) -> None:
    row = len(m)
    col = len(m[0])
    for r in range(row):
        print('[', end='')
        for c in range(col):
            print("{:>2} ".format(m[r][c]), end='')
        print(']')


if __name__ == '__main__':
    m0: Matrix = [
        [1,  2,  3, 4],
        [5, 12,  7, 8],
        [9, 10, 11, 3],
        [4,  3,  1, 2]]
    print("原始矩阵:")
    print_matrix(m0)

    print("滤波后:")
    print_matrix(median_filter(m0))
上一篇 下一篇

猜你喜欢

热点阅读