CS50 pset4 filter模块blur函数执行后整张图片变为单一颜色问题
问题原因与修复方案
你的代码存在两处核心错误,直接导致全图变成单一颜色:
- 最致命的问题:计算邻域像素时,没有把偏移量叠加到当前像素的坐标上,直接用偏移变量
r、c作为下标访问temp数组。所有位置的像素计算时都只会访问图片左上角极小范围的像素,全图所有点都取这几个像素的平均值,最终呈现为统一单色。 - 邻域行偏移的循环范围错误:3x3 box blur的行偏移应该取
-1、0、1三个值,你写的for(int r = -1; r <= 2; r++)会多遍历一个偏移值,即使修复了坐标问题也会导致模糊效果不符合预期。
修正后的代码
// Blur image void blur(int height, int width, RGBTRIPLE image[height][width]) { RGBTRIPLE temp[height][width]; // 先拷贝原图到临时数组,避免修改原图影响后续计算 for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { temp[i][j] = image[i][j]; } } for(int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float count = 0; float red = 0, green = 0, blue = 0; // 3x3邻域遍历,偏移量范围-1到1 for(int r = -1; r <= 1; r++) { for (int c = -1; c <= 1; c++) { // 计算当前邻域像素的实际坐标 int cur_r = i + r; int cur_c = j + c; // 校验坐标是否在图片范围内 if(cur_r >= 0 && cur_r < height && cur_c >= 0 && cur_c < width) { red += temp[cur_r][cur_c].rgbtRed; green += temp[cur_r][cur_c].rgbtGreen; blue += temp[cur_r][cur_c].rgbtBlue; count++; } } } // 计算平均值赋值给原图 image[i][j].rgbtRed = round(red/count); image[i][j].rgbtGreen = round(green/count); image[i][j].rgbtBlue = round(blue/count); } } return; }
内容的提问来源于stack exchange,提问作者Annie
相关产品推荐
相关产品推荐

