问题描述
我正在尝试解决CS50x课程中PSET4滤镜(较少)中的模糊功能。这是问题所在:
模糊
有多种方法可以使图像模糊或柔化。对于此问题,我们将使用“框模糊”功能,该功能通过获取每个像素,并针对每种颜色值,通过平均相邻像素的颜色值来为其赋予新值。
每个像素的新值将是原始像素(形成3x3框)的1行和1列之内的所有像素值的平均值。例如,像素6的每个颜色值都可以通过平均像素1、2、3、5、6、7、9、10和11的原始颜色值来获得(请注意,像素6本身包含在平均)。同样,像素11的颜色值将通过平均像素6、7、8、10、11、12、14、15和16的颜色值获得。
对于沿边缘或角落的像素(如像素15),我们仍将查找1行和1列内的所有像素:在这种情况下,像素为10、11、12、14、15和16。
这是我到目前为止编写的代码:
// Blur image
void blur(int height,int width,RGBTRIPLE image[height][width])
{
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
int red = image[i][j].rgbtRed;
float count = 0.0;
int blurRed = 0;
for (int k = 0; (k <= i + 1) && (k < height); k++)
{
for (int l = 0; (l <= j + 1) && (l < width); L++)
{
int sumRed = image[k][l].rgbtRed;
if ((k - 1 >= 0) && (k + 1 < height))
//these if statements should ensure that the following action is only carried out IF the k/l indices do not exceed height and width
{
sumRed += image[k - 1][l].rgbtRed;
count++;
}
if ((l - 1 >= 0) && (l + 1 < width))
{
sumRed += image[k][l - 1].rgbtRed;
count++;
}
blurRed = roundf(sumRed / count);
}
}
red = blurRed;
}
}
}
尽管我不确定我的解决方案是否正确。运行代码时,出现以下错误消息:
helpers.c:139:45:运行时错误:被零除 helpers.c:139:32:运行时错误:inf超出类型为'int'的可表示值的范围
所以我想知道为什么我的计数器始终保持为0。
期待一些帮助和答案!
解决方法
在第一次迭代中,当k = 0
时,条件k - 1 >= 0
的计算结果为false,0 - 1
不是>= 0
,l
也会发生,结果count
将为0
并执行除以0
。
此外,count
应该是一个整数值,最好是无符号的。为避免此更改导致整数除法舍入问题,您可以稍后将sumRed
或count
强制转换为float
,即 i :
blurRed = roundf((float)sumRed/count);
或者只是将sumRead
声明为float
而不是int
。