@@ -87,14 +87,14 @@ public static unsafe NDArray ToNDArray(this System.Drawing.Bitmap image, bool fl
8787 {
8888 if ( bmpData . Stride / bmpData . Width == 4 ) //1byte-per-color
8989 {
90- return ret . reshape ( 1 , bmpData . Height , bmpData . Width , bmpData . Stride / bmpData . Width ) //reshape
90+ return ReshapeFlatData ( ret , bmpData ) // reshape
9191 [ Slice . All , Slice . All , Slice . All , new Slice ( stop : 3 ) ] //slice
9292 . flat ; //flatten
9393 }
9494
9595 if ( bmpData . Stride / bmpData . Width == 8 ) //2bytes-per-color
9696 {
97- return ret . reshape ( 1 , bmpData . Height , bmpData . Width , bmpData . Stride / bmpData . Width ) //reshape
97+ return ReshapeFlatData ( ret , bmpData ) // reshape
9898 [ Slice . All , Slice . All , Slice . All , new Slice ( stop : 6 ) ] //slice
9999 . flat ; //flatten
100100 }
@@ -106,7 +106,7 @@ public static unsafe NDArray ToNDArray(this System.Drawing.Bitmap image, bool fl
106106 }
107107 else
108108 {
109- ret = ret . reshape ( 1 , bmpData . Height , bmpData . Width , bmpData . Stride / bmpData . Width ) ; //reshape
109+ ret = ReshapeFlatData ( ret , bmpData ) ; //reshape
110110 if ( discardAlpha )
111111 {
112112 if ( ret . shape [ 3 ] == 4 ) //1byte-per-color
@@ -122,6 +122,25 @@ public static unsafe NDArray ToNDArray(this System.Drawing.Bitmap image, bool fl
122122 }
123123 }
124124
125+ /// <summary>
126+ /// Reshapes the flat data to match the size of the bitmap.
127+ /// </summary>
128+ /// <param name="ret">flat 1-dimensional array containing the bitmap data</param>
129+ /// <param name="bmpData">Source bitmap</param>
130+ /// <returns>An 4-dimensional NDArray that holds the bitmap data contained in `ret`</returns>
131+ private static NDArray ReshapeFlatData ( NDArray ret , BitmapData bmpData )
132+ {
133+ var colorBytes = bmpData . Stride / bmpData . Width ;
134+ var strideWidth = bmpData . Stride / colorBytes ; // For odd widths, this width is not equal to bmpData.Width
135+ ret = ret . reshape ( 1 , bmpData . Height , strideWidth , bmpData . Stride / bmpData . Width ) ;
136+ if ( strideWidth != bmpData . Width )
137+ {
138+ ret = ret [ Slice . All , Slice . All , new Slice ( stop : bmpData . Width ) , new Slice ( stop : colorBytes ) ] ;
139+ }
140+
141+ return ret ;
142+ }
143+
125144 /// <summary>
126145 /// Creates <see cref="NDArray"/> from given <see cref="Image"/>.
127146 /// </summary>
0 commit comments