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

CS50棕褐色滤镜(Sepia Filter)像素值计算错误求助:check50检测显示值过高

排查CS50棕褐色滤镜像素值过高的问题

我一眼就发现了代码里的关键错误——你在读取原始像素的绿色和蓝色通道时搞反了!

看这两行代码:

org_green = image[i][j].rgbtBlue;
org_blue = image[i][j].rgbtGreen;

你把原始绿色值赋值给了org_blue,原始蓝色值赋值给了org_green。这就导致棕褐色公式里的权重计算完全用错了通道数值,最终所有像素的计算结果都会偏高,和check50返回的错误完全吻合。

修复后的代码

只需要把这两行的赋值纠正过来,让绿色和蓝色的原始值对应正确:

void sepia(int height, int width, RGBTRIPLE image[height][width]) {
    float org_red = 0;
    float org_green = 0;
    float org_blue = 0;
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            org_red = image[i][j].rgbtRed;
            org_green = image[i][j].rgbtGreen; // 纠正为读取绿色通道
            org_blue = image[i][j].rgbtBlue;   // 纠正为读取蓝色通道
            long sepiaRed = (.393 * org_red + .769 * org_green + .189 * org_blue);
            long sepiaGreen = (.349 * org_red) + .686 * org_green + .168 * org_blue;
            long sepiaBlue = (.272 * org_red + .534 * org_green + .131 * org_blue);
            if (sepiaRed > 255) {
                sepiaRed = 255;
            }
            if (sepiaGreen > 255) {
                sepiaGreen = 255;
            }
            if (sepiaBlue > 255) {
                sepiaBlue = 255;
            }
            image[i][j].rgbtRed = round(sepiaRed);
            image[i][j].rgbtGreen = round(sepiaGreen);
            image[i][j].rgbtBlue = round(sepiaBlue);
        }
    }
    return;
}

为什么这个错误会导致像素值偏高?

棕褐色公式里,绿色通道的权重普遍比蓝色通道高(比如计算sepiaRed时绿色权重是0.769,蓝色是0.189)。你把蓝色值当成绿色代入计算,相当于用了更高的权重去乘原本数值接近甚至更高的通道,最终结果自然会超出预期范围,出现check50里的“像素值过高”问题。

纠正之后,再运行check50应该就能通过所有测试用例了!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:09:07