Search code examples
c#pythonarraysnumpynormalize

Normalize using a given NumPy array (From Python To C#)


I'm trying to convert some Python code into C#, but the difference in code implementation is preventing me from roaching my goal.

I tried creating different arrays and different functions to normalize a C# float array using another array.

Code in Python:

mean_vec = np.array([102.9801, 115.9465, 122.7717])
for i in range(image.shape[0]):
     image[i, :, :] = image[i, :, :] - mean_vec[i]

Code I tried in C#:

Image<Bgr, byte> image = new Image<Bgr, byte>(newBitmap);
Mat newMat = image.Mat;
float[] array = new float[(int)newMat.Total];
newMat.CopyTo(array);
float[] mean_vector = new float[] { 102.9801f, 115.9465f, 122.7717f };

for(int i=0; i<bitmapWidth; i++)
{
    for(int j=0; j<3; j++)
        array[i] = array[i] - mean_vector[j];
}

I am getting the following error

"System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'"


Solution

  •                 for (int k = 0; k < 3; k++)
                    {
                        for (int j = 0; j < newBitmap.Height; j++)
                        {
                            for (int i = 0; i < newBitmap.Width; i++)
                            {
                                floatArray[k, j, i] = (float)Convert.ToDouble(image.Data[j, i, k]) - mean_vec[k];
                            }
                        }
                    }