Skip to content

Commit f8324e8

Browse files
committed
Add object detection example
Add byte type support in Session and Tensor Add pbtxtParser class to utility
1 parent e67152c commit f8324e8

7 files changed

Lines changed: 266 additions & 2 deletions

File tree

‎src/TensorFlowNET.Core/Sessions/BaseSession.cs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ public BaseSession(string target = "", Graph graph = null)
2525
else
2626
{
2727
_graph = graph;
28-
2928
}
3029

3130
_target = UTF8Encoding.UTF8.GetBytes(target);
@@ -212,6 +211,12 @@ private unsafe NDArray fetchValue(IntPtr output)
212211
var str = UTF8Encoding.Default.GetString(bytes, 9, bytes[8]);
213212
nd = np.array(str).reshape();
214213
break;
214+
case TF_DataType.TF_UINT8:
215+
var _bytes = new byte[tensor.size];
216+
for (ulong i = 0; i < tensor.size; i++)
217+
_bytes[i] = *(byte*)(offset + (int)(tensor.itemsize * i));
218+
nd = np.array(_bytes).reshape(ndims);
219+
break;
215220
case TF_DataType.TF_INT16:
216221
var shorts = new short[tensor.size];
217222
for (ulong i = 0; i < tensor.size; i++)

‎src/TensorFlowNET.Core/Sessions/_FetchMapper.cs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,15 @@ public virtual NDArray build_results(List<object> values)
3030
case "Single":
3131
nd.SetData(values.Select(x => (float)x).ToArray());
3232
break;
33+
case "NDArray":
34+
// nd.SetData<NDArray>(values.ToArray());
35+
//NDArray[] arr = new NDArray[values.Count];
36+
//for (int i=0; i<values.Count; i++)
37+
NDArray[] arr = values.Select(x => (NDArray)x).ToArray();
38+
nd = new NDArray(arr);
39+
break;
40+
default:
41+
break;
3342
}
3443

3544
return nd;

‎src/TensorFlowNET.Core/Tensors/Tensor.Creation.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,8 @@ private IntPtr Allocate(NDArray nd)
6767
case "Double":
6868
Marshal.Copy(nd1.Data<double>(), 0, dotHandle, nd.size);
6969
break;
70-
//case "Byte":
70+
case "Byte":
71+
Marshal.Copy(nd1.Data<byte>(), 0, dotHandle, nd.size);
7172
/*var bb = nd.Data<byte>();
7273
var bytes = Marshal.AllocHGlobal(bb.Length);
7374
Marshal.Copy(bb, 0, bytes, bb.Length);

‎src/TensorFlowNET.Core/Tensors/Tensor.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ public TF_DataType ToTFDataType(Type type)
195195
case "Double":
196196
return TF_DataType.TF_DOUBLE;
197197
case "Byte":
198+
return TF_DataType.TF_UINT8;
198199
case "String":
199200
return TF_DataType.TF_STRING;
200201
default:
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
using Newtonsoft.Json;
2+
using NumSharp;
3+
using System;
4+
using System.Collections.Generic;
5+
using System.IO;
6+
using System.Text;
7+
using Tensorflow;
8+
using TensorFlowNET.Examples.Utility;
9+
using System.Drawing;
10+
using System.Drawing.Drawing2D;
11+
using System.Linq;
12+
13+
namespace TensorFlowNET.Examples
14+
{
15+
16+
public class ObjectDetection : Python, IExample
17+
{
18+
public int Priority => 7;
19+
public bool Enabled { get; set; } = true;
20+
public string Name => "Image Recognition";
21+
public float MIN_SCORE = 0.5f;
22+
23+
string modelDir = "ssd_mobilenet_v1_coco_2018_01_28";
24+
string imageDir = "images";
25+
string pbFile = "frozen_inference_graph.pb";
26+
string labelFile = "mscoco_label_map.pbtxt";
27+
string picFile = "input.jpg";
28+
29+
public bool Run()
30+
{
31+
//buildOutputImage(null);
32+
33+
// read in the input image
34+
var imgArr = ReadTensorFromImageFile(Path.Join(imageDir, "input.jpg"));
35+
36+
var graph = new Graph().as_default();
37+
graph.Import(Path.Join(modelDir, pbFile));
38+
39+
var tensorNum = graph.OperationByName("num_detections").outputs[0];
40+
var tensorBoxes = graph.OperationByName("detection_boxes").outputs[0];
41+
var tensorScores = graph.OperationByName("detection_scores").outputs[0];
42+
var tensorClasses = graph.OperationByName("detection_classes").outputs[0];
43+
44+
var imgTensor = graph.OperationByName("image_tensor").outputs[0];
45+
46+
47+
48+
Tensor[] outTensorArr = new Tensor[] { tensorNum, tensorBoxes, tensorScores, tensorClasses };
49+
50+
with(tf.Session(graph), sess =>
51+
{
52+
var results = sess.run(outTensorArr, new FeedItem(imgTensor, imgArr));
53+
54+
//NDArray scores = results.Array.GetValue(2) as NDArray;
55+
56+
//floatscores.Data<float>();
57+
NDArray[] resultArr = results.Data<NDArray>();
58+
59+
//float[] scores = resultArr[2].Data<float>();
60+
buildOutputImage(resultArr);
61+
});
62+
63+
return true;
64+
}
65+
66+
public void PrepareData()
67+
{
68+
if (!Directory.Exists(modelDir))
69+
Directory.CreateDirectory(modelDir);
70+
71+
if (!File.Exists(Path.Join(modelDir, "ssd_mobilenet_v1_coco.tar.gz")))
72+
{
73+
// get model file
74+
string url = "http://download.tensorflow.org/models/object_detection/ssd_mobilenet_v1_coco_2018_01_28.tar.gz";
75+
76+
Utility.Web.Download(url, modelDir, "ssd_mobilenet_v1_coco.tar.gz");
77+
}
78+
79+
if (!File.Exists(Path.Join(modelDir, "frozen_inference_graph.pb")))
80+
{
81+
Utility.Compress.ExtractTGZ(Path.Join(modelDir, "ssd_mobilenet_v1_coco.tar.gz"), "./");
82+
}
83+
84+
85+
// download sample picture
86+
if (!Directory.Exists(imageDir))
87+
Directory.CreateDirectory(imageDir);
88+
89+
if (!File.Exists(Path.Join(imageDir, "input.jpg")))
90+
{
91+
string url = $"https://github.com/tensorflow/models/raw/master/research/object_detection/test_images/image2.jpg";
92+
Utility.Web.Download(url, imageDir, "input.jpg");
93+
}
94+
95+
// download the pbtxt file
96+
if (!File.Exists(Path.Join(modelDir, "mscoco_label_map.pbtxt")))
97+
{
98+
string url = $"https://github.com/tensorflow/models/blob/master/research/object_detection/data/mscoco_label_map.pbtxt";
99+
Utility.Web.Download(url, modelDir, "mscoco_label_map.pbtxt");
100+
}
101+
}
102+
103+
private NDArray ReadTensorFromImageFile(string file_name)
104+
{
105+
return with(tf.Graph().as_default(), graph =>
106+
{
107+
var file_reader = tf.read_file(file_name, "file_reader");
108+
var decodeJpeg = tf.image.decode_jpeg(file_reader, channels: 3, name: "DecodeJpeg");
109+
var casted = tf.cast(decodeJpeg, TF_DataType.TF_UINT8);
110+
var dims_expander = tf.expand_dims(casted, 0);
111+
return with(tf.Session(graph), sess => sess.run(dims_expander));
112+
});
113+
}
114+
115+
private void buildOutputImage(NDArray[] resultArr)
116+
{
117+
// get pbtxt items
118+
PbtxtItems pbTxtItems = PbtxtParser.ParsePbtxtFile(Path.Join(modelDir, "mscoco_label_map.pbtxt"));
119+
120+
// get bitmap
121+
Bitmap bitmap = new Bitmap(Path.Join(imageDir, "input.jpg"));
122+
123+
float[] scores = resultArr[2].Data<float>();
124+
125+
for (int i=0; i<scores.Length; i++)
126+
{
127+
float score = scores[i];
128+
if (score > MIN_SCORE)
129+
{
130+
//var boxes = resultArr[1].Data<float[,,]>();
131+
float[] boxes = resultArr[1].Data<float>();
132+
float top = boxes[i * 4] * bitmap.Height;
133+
float left = boxes[i * 4 + 1] * bitmap.Width;
134+
float bottom = boxes[i * 4 + 2] * bitmap.Height;
135+
float right = boxes[i * 4 + 3] * bitmap.Width;
136+
137+
Rectangle rect = new Rectangle()
138+
{
139+
X = (int)left,
140+
Y = (int)top,
141+
Width = (int)(right - left),
142+
Height = (int)(bottom - top)
143+
};
144+
145+
float[] ids = resultArr[3].Data<float>();
146+
147+
string name = pbTxtItems.items.Where(w => w.id == (int)ids[i]).Select(s=>s.display_name).FirstOrDefault();
148+
149+
drawObjectOnBitmap(bitmap, rect, score, name);
150+
}
151+
}
152+
153+
bitmap.Save(Path.Join(imageDir, "output.jpg"));
154+
}
155+
156+
private void drawObjectOnBitmap(Bitmap bmp, Rectangle rect, float score, string name)
157+
{
158+
using (Graphics graphic = Graphics.FromImage(bmp))
159+
{
160+
graphic.SmoothingMode = SmoothingMode.AntiAlias;
161+
162+
using (Pen pen = new Pen(Color.Red, 2))
163+
{
164+
graphic.DrawRectangle(pen, rect);
165+
166+
Point p = new Point(rect.Right + 5, rect.Top + 5);
167+
string text = string.Format("{0}:{1}%", name, (int)(score * 100));
168+
graphic.DrawString(text, new Font("Verdana", 8), Brushes.Red, p);
169+
}
170+
}
171+
}
172+
}
173+
}

‎test/TensorFlowNET.Examples/TensorFlowNET.Examples.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
<PackageReference Include="Colorful.Console" Version="1.2.9" />
1111
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
1212
<PackageReference Include="SharpZipLib" Version="1.1.0" />
13+
<PackageReference Include="System.Drawing.Common" Version="4.5.1" />
1314
</ItemGroup>
1415

1516
<ItemGroup>
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
using Newtonsoft.Json;
2+
using System;
3+
using System.Collections.Generic;
4+
using System.Text;
5+
6+
namespace TensorFlowNET.Examples.Utility
7+
{
8+
public class PbtxtItem
9+
{
10+
public string name { get; set; }
11+
public int id { get; set; }
12+
public string display_name { get; set; }
13+
}
14+
public class PbtxtItems
15+
{
16+
public List<PbtxtItem> items { get; set; }
17+
}
18+
19+
public class PbtxtParser
20+
{
21+
public static PbtxtItems ParsePbtxtFile(string filePath)
22+
{
23+
string line;
24+
string newText = "{\"items\":[";
25+
26+
try
27+
{
28+
using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
29+
{
30+
31+
while ((line = reader.ReadLine()) != null)
32+
{
33+
string newline = string.Empty;
34+
35+
if (line.Contains("{"))
36+
{
37+
newline = line.Replace("item", "").Trim();
38+
//newText += line.Insert(line.IndexOf("=") + 1, "\"") + "\",";
39+
newText += newline;
40+
}
41+
else if (line.Contains("}"))
42+
{
43+
newText = newText.Remove(newText.Length - 1);
44+
newText += line;
45+
newText += ",";
46+
}
47+
else
48+
{
49+
newline = line.Replace(":", "\":").Trim();
50+
newline = "\"" + newline;// newline.Insert(0, "\"");
51+
newline += ",";
52+
53+
newText += newline;
54+
}
55+
56+
}
57+
58+
newText = newText.Remove(newText.Length - 1);
59+
newText += "]}";
60+
61+
reader.Close();
62+
}
63+
64+
PbtxtItems items = JsonConvert.DeserializeObject<PbtxtItems>(newText);
65+
66+
return items;
67+
}
68+
catch (Exception ex)
69+
{
70+
return null;
71+
}
72+
}
73+
}
74+
}

0 commit comments

Comments
 (0)