有没有一种方法可以将此代码设计为循环?

时间:2020-05-20 14:29:34

标签: c

我正在编写模糊函数,方法是获取最多9个像素(8个像素加[i] [j])的rgb值的平均值。如果语句超出了二维数组的范围,则if语句确保程序不会尝试将像素加到平均值上。代码看起来像是在重复,但是if语句不是真的在重复吗?就像我可以在一个循环中循环一样,使高度从i-1到i + 1,宽度从j-1到j + 1,但是根据要添加的像素,需要使用不同的if语句。有没有一种更好的设计方法?谢谢。

int red = copy[i][j].rgbtRed; //input pixel itself into average. array format copy[height][width].rgbtRed
int n = 1;

if (i != 0 && j != 0)   //input upper left pixel into average
{
    red += copy[i - 1][j - 1].rgbtRed;
    n++;
}
if (i != 0) //pixel directly above
{
    red += copy[i - 1][j].rgbtRed;
    n++;
}
if (i != 0 && j != width - 1) // pixel to top right
{
    red += copy[i - 1][j + 1].rgbtRed;
    n++;
}
if (j != 0) // pixel to left
{
    red += copy[i][j - 1].rgbtRed;
    n++;
}

// and so on and so forth for all the remaining pixels surrounding [i][j]

float redf = (float) red / (float) n; //take average

1 个答案:

答案 0 :(得分:1)

是的。假设您有widthheight作为尺寸,则可以使用ifcontinue跳过那些超出边界的像素:

int red = 0; //input pixel itself into average. array format copy[height][width].rgbtRed
int n = 0;

for (int x=i-1; x<=i+1; ++x) {
    if (x < 0 || x >= height) {
        continue;
    };
    for (int y=j-1; y<=j+1; ++y) {
        if (y < 0 || y >= width) {
            continue;
        }
        red += copy[x][y].rgbtRed;
        n++;
    };
};
float redf = (float) red / (float) n; //take average