将 RGB 的值限制为 255

Capping the value of RGB to 255

我正在研究 CS50 pset4 棕褐色滤镜并尝试使用我的 cap 函数将 RGB 值限制在 255,但它似乎仍然不起作用。任何人都可以建议我在哪里看以及如何解决而不破坏我的学术诚实承诺吗?

我使用了 unsigned char,因为 ide 否则会出错。也不接受 BYTE 作为类型。我试图将它转换为整数,但它也给出了错误。也许我的铸造不正确。如果您想为我添加一个简短的解释以理解我的错误,我将不胜感激,这样我就可以在以后的代码中更有效地解决这个问题。

这是我的 ap 功能:

unsigned char cap(unsigned char a)
{
    if (a > 255)
    {
        a = 255;
    }
    return a;
}

这是 sepia 函数中的代码(在嵌套循环中)

unsigned char x = image[i][j].rgbtRed;
unsigned char y = image[i][j].rgbtGreen;
unsigned char z = image[i][j].rgbtBlue;

image[i][j].rgbtRed = cap(round(x * 0.393 + y * 0.769 + z * 0.189));
image[i][j].rgbtGreen = cap(round(x * 0.349 + y * 0.686 + z * 0.168));
image[i][j].rgbtBlue = cap(round(x * 0.272 + y * 0.534 + z * 0.131));

cap() 函数更改为更像:

unsigned char cap(unsigned int a)

问题在于,当尝试将值传递给 cap() 函数时,C 编译器会截断“大于 255”的值以使它们适合 unsigned char

或者;使用 fmin()fminf() 代替(例如 image[i][j].rgbtBlue = fmin(round(x * 0.272 + y * 0.534 + z * 0.131), 255.0);)。

unsigned char 因为输入参数的类型不包括大于 255 的值(如果字节通常是 8 位)。只需让您的函数接受 intfloatdouble。同样,您可能应该将负数限制为零,尽管它们不会出现在 this 计算中,但可能会出现在其他计算中。

unsigned char cap(int a)
{
    if (a > 255) {
        return 255;
    }
    if (a < 0) {
        return 0;
    }

    return a;
}

至于BYTE,你声明一个typedef:

typedef unsigned char BYTE;

然后使用BYTE