median filter method

The median filtering method is a commonly used smoothing filtering method in digital image processing. Its main principle is to sort the pixel values ​​around each pixel in the image, and then take the median as the new value of the pixel to remove Noise in images and the purpose of preserving edge information. Specific steps are as follows:

  1. Sort the pixel values ​​around the pixel according to size;

  2. Take the sorted median value as the new value of the pixel;

  3. Traverse the entire image and perform the above operations on each pixel;

  4. The final image obtained is the image after median filtering.

The median filtering method is suitable for removing random noises such as salt-and-pepper noise and impulse noise in images, but its effect on non-random noises such as Gaussian noise is not obvious. At the same time, due to the need to sort the pixels around each pixel, the computational complexity is high in large-size filter matrices and high-resolution images, which will affect the processing speed.

Insert image description here

1. C implementation of median filtering method and detailed code explanation

Median filtering is a nonlinear filtering method that replaces the value of a pixel with the median of the pixel values ​​in the neighborhood around the pixel. This filtering method can effectively eliminate noise and retain edge information, so it is widely used in image processing.

The detailed implementation steps are as follows:

  1. Traverse all pixels of the image, and for each pixel, take out a window of size (2k+1)×(2k+1) centered on it, where k is the radius of the median filter. If the pixel is at the edge of the image, the window size will be reduced.

  2. Arrange the grayscale values ​​of all pixels in the window from small to large and find the middle value. If the window size is an even number, the average of the two middle values ​​is taken as the median.

  3. Replace the gray value of that pixel with the median.

  4. Repeat steps 1-3 until the entire image is traversed.

The following is the code to implement the median filtering method in C language:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define WIDTH  512  // 图像宽度
#define HEIGHT 512  // 图像高度
#define RADIUS 2    // 滤波器半径
#define LENGTH (RADIUS*2+1)*(RADIUS*2+1) // 滤波器长度

// 读取二进制图像
void read_image_data(char* filename, unsigned char* data) {
    
    
    FILE* fp = fopen(filename, "rb");
    fread(data, 1, WIDTH*HEIGHT, fp);
    fclose(fp);
}

// 保存二进制图像
void save_image_data(char* filename, unsigned char* data) {
    
    
    FILE* fp = fopen(filename, "wb");
    fwrite(data, 1, WIDTH*HEIGHT, fp);
    fclose(fp);
}

// 中位值滤波器
void median_filter(unsigned char* src, unsigned char* dst) {
    
    
    int i, j, k, l, index;
    unsigned char window[LENGTH];

    for (i = RADIUS; i < HEIGHT - RADIUS; i++) {
    
    
        for (j = RADIUS; j < WIDTH - RADIUS; j++) {
    
    
            index = 0;
            // 取出窗口内所有像素点的灰度值
            for (k = -RADIUS; k <= RADIUS; k++) {
    
    
                for (l = -RADIUS; l <= RADIUS; l++) {
    
    
                    window[index++] = src[(i + k)*WIDTH + (j + l)];
                }
            }
            // 对灰度值进行排序,找到中位数
            for (k = 0; k < LENGTH - 1; k++) {
    
    
                for (l = k + 1; l < LENGTH; l++) {
    
    
                    if (window[k] > window[l]) {
    
    
                        unsigned char temp = window[k];
                        window[k] = window[l];
                        window[l] = temp;
                    }
                }
            }
            // 将该像素点的灰度值替换为中位数
            dst[i*WIDTH + j] = window[LENGTH / 2];
        }
    }
}

int main() {
    
    
    unsigned char src[WIDTH*HEIGHT];
    unsigned char dst[WIDTH*HEIGHT];
    char* input_file = "lena.raw";
    char* output_file = "lena_median.raw";

    // 读取图像数据
    read_image_data(input_file, src);

    // 中位值滤波
    median_filter(src, dst);

    // 保存图像数据
    save_image_data(output_file, dst);

    return 0;
}

Insert image description here

2. C++ implementation of median filtering method and detailed code explanation

Median filtering method is a nonlinear filtering method that is widely used in image processing. The basic principle is to replace the pixel value with the median value of the pixel gray value around the pixel point to achieve the purpose of smoothing and denoising. The following is the code and detailed explanation of the median filtering method in C++.

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    
    
    Mat image = imread("lena.png", IMREAD_GRAYSCALE); //读取灰度图像
    Mat dst = image.clone(); //创建一个与原图像大小一致的Mat对象
    int ksize = 3; //设置滤波器大小,为3x3
    int n = ksize / 2; //计算滤波器半径
    for (int i = n; i < image.rows - n; ++i) //遍历图像的每一个像素点
    {
    
    
        for (int j = n; j < image.cols - n; ++j)
        {
    
    
            vector<uchar> pixels; //定义存储像素值的容器
            for (int k = -n; k <= n; ++k) //遍历滤波器模板
            {
    
    
                for (int l = -n; l <= n; ++l)
                {
    
    
                    pixels.push_back(image.at<uchar>(i + k, j + l)); //将像素值插入容器
                }
            }
            sort(pixels.begin(), pixels.end()); //对容器中的像素值进行排序
            dst.at<uchar>(i, j) = pixels[pixels.size() / 2]; //取中位数值并赋给目标图像
        }
    }
    imshow("src", image);
    imshow("dst", dst);
    waitKey();
    return 0;
}

Detailed code explanation:

  1. Import OpenCV and iostream libraries.

  2. Use namespaces cv and std.

  3. Read the grayscale image and create a Mat object with the same size as the original image.

  4. Set the filter size to 3x3.

  5. Calculate the filter radius.

  6. Traverse each pixel of the image, starting from the upper left corner of the filter.

  7. Defines a container to store pixel values.

  8. Traverse the filter template, starting from the upper left corner of the template.

  9. Insert pixel values ​​into the container.

  10. Sorts the pixel values ​​in a container.

  11. Take the median value and assign it to the target image.

  12. Display the original image and the median filtered image.

  13. Wait for the user to press any key before the program ends.

It should be noted that when implementing the median filtering method, special processing of the image edges is required. Here, a simple edge filling method is used: copy the edge value to an area within the edge radius width of pixels.

references:

[1] C++ implementation of median filtering algorithm https://www.jianshu.com/p/7dabcfe7c1b0

[2] Median filter https://zh.wikipedia.org/wiki/%E4%B8%AD%E5%80%BC%E6%BB%A4%E6%B3%A2

Insert image description here

3. Java implementation of median filtering method and detailed code explanation

Median filtering is a common image processing method used to remove noise in images. Its basic idea is to use a sliding window to move on the image, sort the pixels in the window according to size, and then take the middle value as the pixel value at that position. This can remove noise within a certain range without excessively blurring image edges and details.

The method of implementing median filtering in Java is very simple. You only need to write code according to the above ideas. Here is an example code for implementing a 3x3 median filter:

public static int[][] medianFilter(int[][] input) {
    
    
    int rows = input.length;
    int cols = input[0].length;

    // 新建输出矩阵
    int[][] output = new int[rows][cols];

    // 对于每个像素,以其为中心构建 3x3 的窗口
    for (int i = 1; i < rows - 1; i++) {
    
    
        for (int j = 1; j < cols - 1; j++) {
    
    
            int[] window = new int[9];
            int index = 0;
            for (int k = -1; k <= 1; k++) {
    
    
                for (int l = -1; l <= 1; l++) {
    
    
                    window[index++] = input[i + k][j + l];
                }
            }

            // 将窗口中的像素排序
            Arrays.sort(window);

            // 取中间的值作为该位置的像素值
            output[i][j] = window[4];
        }
    }

    return output;
}

In this example, we first create a new output matrix of the same size as the input matrix. Then for each pixel, build a 3x3 window centered on it, sort the pixels in the window according to size, and take the middle value as the pixel value at that location. Finally, return the output matrix.

It should be noted that this implementation method may cause out-of-bounds problems for pixels on the boundary, which requires additional processing. In addition, the sorting operation in this implementation may have an impact on performance, so optimization may be required in practical applications.

Guess you like

Origin blog.csdn.net/weixin_47225948/article/details/133125499