Skip to content

Commit 2ac92fc

Browse files
captainstmigueldeicaza
authored andcommitted
Add CreateTensorFromImageFileAlt function (migueldeicaza#421)
An alternative function that convert directly the pixel values of a bitmap to a (1,H,W,3) shape matrix, which is converted to a tensor. This function is fast and gives better results for Object Detection Example.
1 parent a8a280e commit 2ac92fc

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Examples/ExampleCommon/ImageUtil.cs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,5 +66,33 @@ private static TFGraph ConstructGraphToNormalizeImage (out TFOutput input, out T
6666

6767
return graph;
6868
}
69+
70+
public static unsafe TFTensor CreateTensorFromImageFileAlt(string inputFileName, TFDataType destinationDataType = TFDataType.Float)
71+
{
72+
Bitmap bitmap = new Bitmap(inputFileName);
73+
74+
BitmapData data = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
75+
76+
var matrix = new byte[1, bitmap.Height, bitmap.Width, 3];
77+
78+
byte* scan0 = (byte*)data.Scan0.ToPointer();
79+
80+
for (int i = 0; i < data.Height; i++)
81+
{
82+
for (int j = 0; j < data.Width; j++)
83+
{
84+
byte* pixelData = scan0 + i * data.Stride + j * 3;
85+
matrix[0, i, j, 0] = pixelData[2];
86+
matrix[0, i, j, 1] = pixelData[1];
87+
matrix[0, i, j, 2] = pixelData[0];
88+
}
89+
}
90+
91+
bitmap.UnlockBits(data);
92+
93+
TFTensor tensor = matrix;
94+
95+
return tensor;
96+
}
6997
}
7098
}

0 commit comments

Comments
 (0)