Skip to content

Bitmap Extensions

Eli Belash edited this page Nov 7, 2019 · 5 revisions

We provide extension methods via a separate project NumSharp.Bitmap.

//install nuget package
PM> Install-Package NumSharp.Bitmap
using NumSharp;

NDArray nd = bitmap.ToNDArray(flat: false, copy: true, discardAlpha: true);
Bitmap bmp = nd.ToBitmap();
Assert.IsTrue(bmp content equals to original bitmap without alpha);

The source is a 300-lines file, (see more) and provides various extensions and overloads such as support for BitmapData (via AsNDArray) and conversion backwards to Bitmap (via ToBitmap).

Flattening

When calling ToNDArray and specifiying:

When specifying flat: true: returns NDArray of 1-d of pixels: R1G1B1R2G2B2 ... RnGnBn (or with alpha, depends on the bitmap format) where n is the amount of pixels times byte_per_pixel in the image.
When specifying flat: false: returns a 4-d NDArray shaped: (1, bmpData.Height, bmpData.Width, byte_per_pixel)

byte_per_pixel is valued 3 for RGB and 4 for RGBA. depends on PixelFormat of the bitmap (you can find out using format.ToBytesPerPixel() extension).

Copying

When specifying copy: true, the Bitmap.LockBits is called and then copies the data to a new then finally releasing the locked bits.
When specifying copy: false, It'll call Bitmap.LockBits, wraps the BitmapData.Scan0 with an NDArray and call Bitmap.UnlockBits only when the returned NDArray and its non-copy slices are be collected by the GC.

Clone this wiki locally