[英]Grayscale to RGB: Pixel color is set with wrong value
I have a program that reads the grayscale (0 - 255) value of a pixel and changes it to an RGB color (formula see code).我有一个程序可以读取像素的灰度(0 - 255)值并将其更改为 RGB 颜色(公式参见代码)。
Here is my code:这是我的代码:
Bitmap img = new Bitmap(@"somepath");
Bitmap new_img = new Bitmap(img.Width, img.Height);
for (int i = 0; i < img.Width; i++)
{
for (int j = 0; j < img.Height; j++)
{
Color pixel = img.GetPixel(i, j);
Color my = new Color();
int R_new = 0;
if (pixel.R > 126)
{
R_new = (pixel.R -127) / 128 * 255;
}
int B_new = 0;
if (pixel.B < 128) {
B_new = (1 - pixel.R / 127) * 255;
}
int G_new = 0;
if (pixel.G < 128) {
G_new = pixel.R/127 * 255;
}
my = Color.FromArgb(R_new, G_new, B_new);
new_img.SetPixel(i, j, my);
}
}
new_img.Save(@"C:somepath");
In the following picture在下图中
you can see the green-value of the old pixel is 6 and of the new pixel it is set with 255, which is wrong.
您可以看到旧像素的绿色值为 6,而新像素的绿色值设置为 255,这是错误的。 According to the formula it should be set at 12.
根据公式,它应该设置为 12。
Here is my question: Why is the value of the pixel set wrong?这是我的问题:为什么像素集的值是错误的?
You have two problems.你有两个问题。
#1: You're passing the blue value in place of the green value. #1:您传递的是蓝色值而不是绿色值。 Check the expected order of arguments :
检查arguments 的预期顺序:
Color.FromArgb(int red,
int green, int blue)
#2: B_new
is 255
due to how integer division is handled: #2:
B_new
是255
,因为integer 划分是如何处理的:
For the operands of integer types, the result of the
/
operator is of an integer type and equals the quotient of the two operands rounded towards zero:对于 integer 类型的操作数,
/
运算符的结果是 integer 类型,并且等于两个操作数的商,四舍五入到零:
(1 - 6 / 127) * 255 // becomes 255
So, 6 / 127
equals 0.047244094488189
but it's rounded down to zero... making your formula:所以,
6 / 127
等于0.047244094488189
但它被四舍五入到零......制作你的公式:
(1 - 0) * 255 // becomes 255
Make at least one of your division terms a floating point type and you'll get a decimal value:将至少一个除法项设为浮点类型,您将得到一个十进制值:
(1 - pixel.R /
127.0) * 255 // becomes 242.9527559055118
... which you'll then have to convert to an int
to conform to the method signature of Color.FromArgb(int, int, int)
. ...然后您必须将其转换为
int
以符合Color.FromArgb(int, int, int)
的方法签名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.