Get and Set Pixel Gray scale image Using Emgu CV

2020-07-22 19:36发布

问题:

I am trying to get and set pixels of a gray scale image by using emgu Cv with C#. If I use a large image size this error message occurs: "Index was outside the bounds of the array."

If I use an image 200x200 or less then there is no error but I don't understand why.

Following is my code:

 Image<Gray , byte> grayImage;
--------------------------------------------------------------------

        for (int v = 0; v < grayImage.Height; v++)
        {
            for (int u = 0; u < grayImage.Width; u++)
            {
                byte a = grayImage.Data[u , v , 0]; //Get Pixel Color | fast way
                byte b = (byte)(myHist[a] * (K - 1) / M);
                grayImage.Data[u , v , 0] = b; //Set Pixel Color | fast way
            }
        }
--------------------------------------------------------------------

http://i306.photobucket.com/albums/nn262/neji1909/9-6-25565-10-39.png

Please help me and sorry I am not good at English.

回答1:

That's because the x and y are inverted in the Data array. You should change your code this way (invert u and v):

    for (int v = 0; v < grayImage.Height; v++)
    {
        for (int u = 0; u < grayImage.Width; u++)
        {
            byte a = grayImage.Data[v , u , 0]; //Get Pixel Color | fast way
            byte b = (byte)(myHist[a] * (K - 1) / M);
            grayImage.Data[v , u , 0] = b; //Set Pixel Color | fast way
        }
    }

See also Iterate over pixels of an image with emgu cv



回答2:

you are not indexing by (x,y) but by (row, col) - inverted. When you used 200x200 image it was the same whether you used width or height.

you could do that by using pointers (much faster) because if you are using indexing EmguCV internally uses calls to opencv for an every pixel.

so:

byte* ptr = (byte*)image.MIplImage.imageData;
int stride = image.MIplImage.widthStep;

int width = image.Width;
int height = image.Height;

for(int j = 0; j < height; j++) 
{
  for(int i = 0; i < width; i++)
  {
     ptr[i] = (byte)(myHist[a] * (K - 1) / M);
  }

  ptr += stride;
} 


标签: emgucv