Skip to content

Commit

Permalink
Fixes #459 NDArray.ToBitmap() does not handle images with odd width
Browse files Browse the repository at this point in the history
  • Loading branch information
BramClocktimizer authored and Oceania2018 committed Dec 17, 2023
1 parent 62ed1aa commit 49c4c1a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
7 changes: 5 additions & 2 deletions src/NumSharp.Bitmap/np_.extensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,8 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix

//if flat then initialize based on given format
if (nd.ndim == 1 && format != PixelFormat.DontCare)
nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatch.

nd = nd.reshape(1, height, width, format.ToBytesPerPixel()); //theres a check internally for size mismatc
if (nd.ndim != 4)
throw new ArgumentException("ndarray was expected to be of 4-dimensions, (1, bmpData.Height, bmpData.Width, bytesPerPixel)");

Expand All @@ -237,6 +237,9 @@ public static unsafe Bitmap ToBitmap(this NDArray nd, int width, int height, Pix

var ret = new Bitmap(width, height, format);
var bitdata = ret.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, format);
if (bitdata.Stride != width * format.ToBytesPerPixel())
nd = np.concatenate((nd, np.zeros((1, height, 1, format.ToBytesPerPixel())).astype(NPTypeCode.Byte)), 2);

try
{
var dst = new ArraySlice<byte>(new UnmanagedMemoryBlock<byte>((byte*)bitdata.Scan0, bitdata.Stride * bitdata.Height));
Expand Down
10 changes: 10 additions & 0 deletions test/NumSharp.UnitTest/NumSharp.Bitmap/BitmapWithAlphaTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,16 @@ public void ToNDArray_Odd_Width()
var nd = bitmap.ToNDArray(discardAlpha: false, copy: false);
nd.Should().BeShaped(1, 554, 475, 3);
}

[TestMethod]
public void ToBitmap_Odd_Width()
{
var bitmap = EmbeddedBitmap("odd-width");
var nd = bitmap.ToNDArray(discardAlpha: false, copy: false);
var bitmap2 = nd.ToBitmap();
bitmap2.Width.Should().Be(bitmap.Width);
bitmap2.Height.Should().Be(bitmap.Height);
}

[TestMethod]
public void ToNDArray_Case5_flat()
Expand Down

0 comments on commit 49c4c1a

Please sign in to comment.