Pregunta

I run this code in c# language ,but there is error that

"value of "257 is not valid for red.red should be greater than or equal to 0 and less than or equal to 255"

How can I correct this error?

Int32[,] Y1= new Int32[width,height];//R,G,B not empty array       
Int32[,] R= new Int32[width,height];       
Int32[,] G= new Int32[width,height];      
Int32[,] B= new Int32[width,height];        
Bitmap bmp=new Bitmap[width,height];
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
{

   Y1[x, y] = Convert.ToInt32(0.39 * R[x, y] + 0.59 * G[x, y] + 0.12 * B[x, y]);                                
   bmp.SetPixel(x, y, Color.FromArgb(Y1[x,y],Y1[x,y],Y1[x,y]));
}
pictureBox1.Image = bmp;

I know that "Color.FromArgb(Y1[x,y],Y1[x,y],Y1[x,y])" out of range but how can I

correct it ?

¿Fue útil?

Solución

You're probably trying to convert to grayscale. There are two things you should do:

  1. Your weights are wrong. The correct weights are 0.299, 0.587 and 0.114.
  2. Apply a cap using Math.Min(). Something like:

    Y1[x, y] = Math.Min(255, Convert.ToInt32(0.299 * R[x, y] + 0.587 * G[x, y] + 0.114 * B[x, y]));

The cap is there only to make sure our formula never exceeds the max byte value.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top