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

CS50第4次作业filter-more模糊函数异常,输出图片怪异求助

Fix for CS50 Filter-More Blur Function

The core issue in your code is integer overflow from using BYTE type for color sums. BYTE is an unsigned 8-bit value (max 255), but summing up to 9 pixels (each with RGB values up to 255) can result in totals up to 2295—way beyond what a BYTE can hold. This causes sums to wrap around incorrectly, leading to distorted blur effects.

Solution

Change the sum variables from BYTE to int to accommodate larger values:

// Replace this line:
BYTE blue_sum, green_sum, red_sum;

// With this:
int blue_sum, green_sum, red_sum;

Corrected Blur Function

// Blur image
void blur(int height, int width, RGBTRIPLE image[height][width])
{
    RGBTRIPLE temp[height][width];
    // Use int instead of BYTE for sums to prevent overflow
    int blue_sum, green_sum, red_sum;
    float counter;
    // inclusive lower and upper bounds
    int lower_bound_row, upper_bound_row, lower_bound_col, upper_bound_col;
    for (int i = 0; i < height; i++)
    {
        lower_bound_row = (i - 1 < 0)? i : i - 1;
        upper_bound_row = (i + 1 == height)? i : i + 1;
        for (int j = 0; j < width; j++)
        {
            blue_sum = 0; green_sum = 0; red_sum = 0;
            counter = 0.00;
            lower_bound_col = (j - 1 < 0)? j : j - 1;
            upper_bound_col = (j + 1 == width)? j : j + 1;

            // Adding the color values of neighboring pixels
            for (int a = lower_bound_row; a <= upper_bound_row; a++)
            {
                for (int b = lower_bound_col; b <= upper_bound_col; b++)
                {
                    blue_sum += image[a][b].rgbtBlue;
                    green_sum += image[a][b].rgbtGreen;
                    red_sum += image[a][b].rgbtRed;
                    counter++;
                }
            }
            // Dividing the sums by no. of neighing pixels to calculate the averages
            temp[i][j].rgbtBlue = round(blue_sum / counter);
            temp[i][j].rgbtGreen = round(green_sum / counter);
            temp[i][j].rgbtRed = round(red_sum / counter);
        }
    }
    for (int i = 0; i < height; i++)
    {
        for (int j = 0; j < width; j++)
        {
            image[i][j] = temp[i][j];
        }
    }
    return;
}

Additional Notes

  • Using int for sums ensures you can hold the total of up to 9×255=2295 without overflow.
  • For debugging, add print statements (e.g., printf("Blue sum: %d\n", blue_sum);) to verify sum values before division.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:17:40