You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Java是否有内置数组中位数函数?求中值滤波代码

Android Java中值滤波实现方案

内置中位数函数说明

Android Studio中的Java标准库及Android SDK没有专门针对图像通道二维数组的内置中位数计算函数,也无直接支持带掩膜的中值滤波的API,需手动实现核心逻辑。

带掩膜的中值滤波实现代码

以下是针对RGB三通道二维数组的3x3掩膜中值滤波实现(可按需调整掩膜尺寸):

public class MedianFilter {
    // 可修改为5、7等奇数以调整掩膜大小
    private static final int MASK_SIZE = 3;
    private static final int MASK_RADIUS = MASK_SIZE / 2;

    // 对单通道应用中值滤波
    public static int[][] applyMedianFilter(int[][] channel) {
        int height = channel.length;
        int width = channel[0].length;
        int[][] filteredChannel = new int[height][width];

        // 遍历图像每个像素
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int[] maskValues = new int[MASK_SIZE * MASK_SIZE];
                int idx = 0;

                // 遍历掩膜范围内的所有像素
                for (int dy = -MASK_RADIUS; dy <= MASK_RADIUS; dy++) {
                    for (int dx = -MASK_RADIUS; dx <= MASK_RADIUS; dx++) {
                        // 边界处理:超出图像范围时取边缘像素值
                        int targetY = Math.max(0, Math.min(height - 1, y + dy));
                        int targetX = Math.max(0, Math.min(width - 1, x + dx));
                        maskValues[idx++] = channel[targetY][targetX];
                    }
                }

                // 排序后取中位数作为当前像素的新值
                java.util.Arrays.sort(maskValues);
                filteredChannel[y][x] = maskValues[MASK_SIZE * MASK_SIZE / 2];
            }
        }
        return filteredChannel;
    }

    // 批量处理RGB三通道
    public static void processRGBChannels(int[][] redChan, int[][] greenChan, int[][] blueChan) {
        int[][] filteredRed = applyMedianFilter(redChan);
        int[][] filteredGreen = applyMedianFilter(greenChan);
        int[][] filteredBlue = applyMedianFilter(blueChan);

        // 将滤波结果覆盖原通道数组(也可返回新数组,按需调整)
        System.arraycopy(filteredRed, 0, redChan, 0, filteredRed.length);
        System.arraycopy(filteredGreen, 0, greenChan, 0, filteredGreen.length);
        System.arraycopy(filteredBlue, 0, blueChan, 0, filteredBlue.length);
    }
}

代码使用说明

  • 掩膜调整:若需要更强的降噪效果,可将MASK_SIZE改为5、7等奇数,掩膜越大降噪能力越强,但图像细节损失也会增加。
  • 边界处理:当前采用复制边缘像素的方式处理边界,避免数组越界,你也可以根据需求改为填充固定值(如0)或直接跳过边缘像素。
  • 通道处理:调用processRGBChannels方法即可一次性完成红、绿、蓝三个通道的中值滤波,处理后的结果会直接覆盖原通道数组。

内容的提问来源于stack exchange,提问作者Suadad Najim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 03:55:16