I have a requirement where I need to extract pixels of a given rectangle within an image byte[]
.
More specifically I have an image where I have narrowed an area that I wish to return and keep and the remainder discard. In my case I'm performing face recognition in real time so I don't want to store unnecessary data but obviously this could be useful elsewhere.
public static byte[] ExtractPixelsFromImage(this byte[] pixels, int top, int left, int width, int height, int horizontalResolution)
{
List<byte> result = new List<byte>();
int bytesPerPixel = 4;
int rowLength = horizontalResolution * bytesPerPixel;
int rowLeftPixelStart = (rowLength * top) + (left * bytesPerPixel);
for (int i = 0; i < height; i++)
{
int currentPixelStart = (rowLength * i) + rowLeftPixelStart;
result.AddRange(pixels.Skip(currentPixelStart).Take(width * bytesPerPixel));
}
return result.ToArray();
}
This method has been responsible for the vast amount of CPU time my application is using and I'm hoping to improve this.
The obvious suggestion is to remove the LINQ, but beyond this, is there anything else that can be improved?
List<byte> result = new List<byte>(bytesPerPixel * width * height);
\$\endgroup\$Buffer.BlockCopy
for fast array block copying. \$\endgroup\$