[英]Capping the value of RGB to 255
I'm working on CS50 pset4 sepia filter and trying to cap the RGB value at 255 with my cap
function, but it seems still doesn't working.我正在研究 CS50 pset4 棕褐色滤镜,并试图用我的
cap
函数将 RGB 值限制在 255,但它似乎仍然不起作用。 Can anyone advice me where to look and how to fix without spoiling my academic honesty commitment?任何人都可以建议我去哪里寻找以及如何在不破坏我的学术诚实承诺的情况下解决问题吗?
I've used unsigned char
because ide gives error otherwise.我使用了
unsigned char
因为 ide 否则会出错。 Also doesn't accept BYTE
as a type.也不接受
BYTE
作为类型。 I've tried to cast it to integer but it gives error too.我试图将它转换为整数,但它也给出了错误。 Maybe my casting was not correctly.
也许我的铸造不正确。 I'll appreciate if you want to add a brief explaination for me to understand my mistake so I could be more efficient in my future code regarding this issue.
如果您想为我添加一个简短的解释以理解我的错误,我将不胜感激,这样我就可以在以后关于这个问题的代码中更有效率。
This my ap function:这是我的 ap 功能:
unsigned char cap(unsigned char a)
{
if (a > 255)
{
a = 255;
}
return a;
}
and this the code in sepia function (in the nested loops)这是棕褐色函数中的代码(在嵌套循环中)
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));
unsigned char
as the type of input parameter excludes values > 255 (if bytes are 8 bits as they commonly are). unsigned char
作为输入参数的类型不包括大于 255 的值(如果字节通常是 8 位)。 Just make your function accept an int
or float
or double
.只需让您的函数接受
int
或float
或double
。 Likewise you should probably clamp negative numbers to zero, though they won't occur in this calculation but might occur in some other.同样,您可能应该将负数限制为零,尽管它们不会出现在此计算中,但可能会出现在其他计算中。
unsigned char cap(int a)
{
if (a > 255) {
return 255;
}
if (a < 0) {
return 0;
}
return a;
}
As for BYTE
, you declare a typedef:至于
BYTE
,你声明一个 typedef:
typedef unsigned char BYTE;
and use BYTE
thereafter.然后使用
BYTE
。
Change the cap()
function to be more like:将
cap()
函数更改为更像:
unsigned char cap(unsigned int a)
The problem is that the C compiler truncates "larger than 255" values to make them fit in an unsigned char
when trying to pass the values to the cap()
function.问题在于,当尝试将值传递给
cap()
函数时,C 编译器会截断“大于 255”的值以使它们适合unsigned char
。
Alternatively;或者; use
fmin()
or fminf()
instead (eg image[i][j].rgbtBlue = fmin(round(x * 0.272 + y * 0.534 + z * 0.131), 255.0);
).使用
fmin()
或fminf()
代替(例如image[i][j].rgbtBlue = fmin(round(x * 0.272 + y * 0.534 + z * 0.131), 255.0);
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.