-
Notifications
You must be signed in to change notification settings - Fork 194
Bitmap Extensions
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
).
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).
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.