3

I have a 2D array declared as new byte[w, h]. I want to crop out a sub-section of this array given coordinates (x1,y1)-(x2,y2). What's the quickest way to do this? Are there any methods for "slicing" 2D arrays?

4

2 回答 2

1

I cant come up with a faster way, but you could use two nested loops:

byte[,] array2 = new byte[x2 - x1, y2 - y1];
for (int i = x1; i < x2; i++)
{
    for (int j = y1; j < y2; j++)
    {
        array2[i-x1, j-y1] = array[i, j];
    }
}

For a jagged array you could use a linq query:

IEnumerable<byte> x = array3.Skip(x1)
                            .Take(x2-x1)
                            .SelectMany(a => a.Skip(y1).Take(y2-y1));
于 2013-05-21T03:43:14.350 回答
1

You could use Array.Copy:

int w2 = x2 - x1 + 1;
int h2 = y2 - y1 + 1;
byte[,] array2 = new byte[w2, h2];
for (int i = 0; i < w2; i++)
{
    Array.Copy(array1, (i+x1)*h + y1, array2, i*h2, h2);
}

This might be faster for large arrays. The two nested loops are however more readable.

于 2013-05-21T08:34:13.447 回答