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

C语言实现的box blur模糊滤镜函数运行结果不符合预期如何修复

模糊滤镜代码问题修复

核心错误原因

你当前代码的核心问题是**直接在原始图像数组上修改像素值:计算当前像素的模糊值时,上方、左方已经遍历过的像素已经被替换成了模糊后的新值,后续采样计算时用的不是原始图像的像素值,导致平均值计算错误,最终输出的颜色值普遍高于预期值。
角落像素测试通过的原因是:四个角落像素计算时用到的采样像素均未被提前修改,所以结果符合预期,和你给出的测试结果完全匹配。

修复方案

你需要先创建一个临时数组存储原始图像的所有像素值,所有模糊计算全部基于临时数组的原始值计算,最后再把计算得到的新值写入原始图像数组即可。

修复后的参考代码

#include <math.h>
#include <stdlib.h>

void blur(int height, int width, RGBTRIPLE image[height][width])
{
    // 创建临时数组存储原始图像数据
    RGBTRIPLE (*temp)[width] = malloc(sizeof(RGBTRIPLE[height][width]));
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            temp[i][j] = image[i][j];
        }
    }

    // 遍历每个像素计算模糊值
    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            int sumofred = 0, sumofgreen = 0, sumofblue = 0;
            float pixelscount = 0;

            // 确定采样框边界
            int startrow = (row == 0 ? 0 : row - 1;
            int endrow = (row == height - 1 ? height - 1 : row + 1;
            int startcol = (col == 0 ? 0 : col - 1;
            int endcol = (col == width - 1 ? width - 1 : col + 1;

            // 从临时数组采样计算平均值
            for (int i = startrow; i <= endrow; i++)
            {
                for (int j = startcol; j <= endcol; j++)
                {
                    sumofred += temp[i][j].rgbtRed;
                    sumofgreen += temp[i][j].rgbtGreen;
                    sumofblue += temp[i][j].rgbtBlue;
                    pixelscount++;
                }
            }

            // 计算并赋值新值到原始图像
            image[row][col].rgbtRed = round(sumofred / pixelscount);
            image[row][col].rgbtGreen = round(sumofgreen / pixelscount);
            image[row][col].rgbtBlue = round(sumofblue / pixelscount);
        }
    }

    // 释放临时数组内存
    free(temp);
    return;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:18:02