CS50 PSET4 blur模糊功能编译通过却提示invalid or unsupported image格式问题
问题原因
你代码里的两层内层循环出现了循环变量自增错误,直接导致数组越界访问,破坏了BMP图像的文件头结构,所以输出时程序识别不到合法的图像格式:
- 遍历邻域行的循环
for (int x = i-1 ; x <= i+1 ; i++)中,错误地对上层循环变量i做了自增,而非当前循环变量x,会导致i的值快速超出height的合法范围,触发数组越界 - 遍历邻域列的循环
for (int y = j-1 ; y <= j+1 ; j++)中,错误地对上层循环变量j做了自增,而非当前循环变量y,同样会引发越界问题
越界访问会篡改内存中存储在图像数组之后的BMP文件头数据,最终输出的文件头不符合BMP格式规范,就会触发你看到的格式错误。
解决方案
只需要修正两层内层循环的自增变量即可,修改后的核心代码如下:
RGBTRIPLE temp[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { float red_sum = 0; float blue_sum = 0; float green_sum = 0; int count = 0; // 修正x循环的自增变量为x for (int x = i-1 ; x <= i+1 ; x++) { // 修正y循环的自增变量为y for (int y = j-1 ; y <= j+1 ; y++) { if ( x >= 0 && x < height && y >= 0 && y < width ) { red_sum += image[x][y].rgbtRed; blue_sum += image[x][y].rgbtBlue; green_sum += image[x][y].rgbtGreen; count ++; } } } int red_avg = round(red_sum/count); int blue_avg = round(blue_sum/count); int green_avg = round(green_sum/count); temp[i][j].rgbtRed = red_avg; temp[i][j].rgbtBlue = blue_avg; temp[i][j].rgbtGreen = green_avg; } } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { image[i][j]=temp[i][j]; } }
修改后重新编译运行即可正常输出模糊后的图像。
内容的提问来源于stack exchange,提问作者Jirapath Tharasena
相关产品推荐
相关产品推荐

