這裡是一個使用 TensorFlow.NET (TF.NET) 進行物件辨識的 C# 程式碼,該程式碼會:

  1. 載入預訓練的 TensorFlow 模型(如 SSD 或 YOLO)。
  2. 讀取圖片並進行物件偵測
  3. 顯示偵測結果

安裝 TensorFlow.NET

首先,確保你已安裝 TensorFlow.NET,可以使用 NuGet 來安裝:

sh

dotnet add package TensorFlow.NET
dotnet add package SciSharp.TensorFlow.Redist

 


C# 物件辨識程式碼

csharp

using System;
using System.IO;
using Tensorflow;
using Tensorflow.NumPy;
using static Tensorflow.Binding;
using Tensorflow.Keras.Engine;
using Tensorflow.Keras.Layers;
using Tensorflow.Keras.Models;
using Tensorflow.Keras.Utils;

class Program
{
static void Main(string[] args)
{
string modelPath = "ssd_mobilenet_v2.pb"; // 這裡放預訓練模型
string imagePath = "test.jpg"; // 測試圖片

// 讀取 TensorFlow 模型
var graph = new Graph().as_default();
var session = new Session(graph);

// 載入模型
byte[] modelBytes = File.ReadAllBytes(modelPath);
session.graph.Import(modelBytes);

// 讀取圖片並轉換為 Tensor
NDArray imageArray = LoadImage(imagePath);
Tensor inputTensor = graph.OperationByName("image_tensor").output(0);
Tensor detectionBoxes = graph.OperationByName("detection_boxes").output(0);
Tensor detectionScores = graph.OperationByName("detection_scores").output(0);
Tensor detectionClasses = graph.OperationByName("detection_classes").output(0);

// 執行物件偵測
var results = session.run(new[] { detectionBoxes, detectionScores, detectionClasses }, new FeedItem(inputTensor, imageArray));

// 處理結果
ProcessResults(results);
}

static NDArray LoadImage(string path)
{
byte[] imageBytes = File.ReadAllBytes(path);
NDArray imageArray = np.array(imageBytes);
imageArray = np.reshape(imageArray, new Shape(1, 300, 300, 3)); // 轉換為 TensorFlow 可接受格式
return imageArray;
}

static void ProcessResults(NDArray[] results)
{
Console.WriteLine("偵測到的物件:");
for (int i = 0; i < results[0].shape[1]; i++)
{
float score = results[1][0, i];
if (score > 0.5) // 只顯示高信心度的物件
{
Console.WriteLine($"物件 {i}: 信心度 {score * 100}%");
}
}
}
}

 

程式說明

  1. 載入 TensorFlow 模型 (ssd_mobilenet_v2.pb)

    • 這是一個預訓練的物件偵測模型(可以使用 TensorFlow Model Zoo)。
  2. 讀取圖片並轉換成 Tensor

    • 轉換為 [1, 300, 300, 3] 以符合模型輸入格式。
  3. 執行 TensorFlow.NET 進行物件偵測

    • 提取偵測的物件邊界框 (detection_boxes)。
    • 提取偵測的分類 (detection_classes)。
    • 提取信心度 (detection_scores)。
  4. 輸出辨識結果

    • 只顯示 信心度大於 50% 的物件。

如何取得 ssd_mobilenet_v2.pb 模型

  1. 下載預訓練模型:
  2. 解壓縮後,你會找到 frozen_inference_graph.pb,請將其更名為 ssd_mobilenet_v2.pb,放入程式目錄。

適用場景

監控畫面辨識產品分類與檢測自動駕駛影像辨識

這個 C# 程式利用 TensorFlow.NET 進行物件偵測,適用於 Windows/Linux 的 .NET 開發環境

使用 TensorFlow.NET (TF.NET) 進行物件偵測的 穩定度與可靠性 主要取決於幾個因素:


✅ 穩定性與可靠性分析

影響因素評估結果可能風險
TF.NET 框架穩定性 較穩定,但比 TensorFlow 原生版本更新較慢 TF.NET 可能落後 TensorFlow 官方版本
預訓練模型 (SSD MobileNet v2) 穩定,適用於一般物件偵測 模型準確度受限於訓練數據,對小物件偵測效果較差
執行效能 可接受,支援 CPU/GPU 需要安裝正確的 TensorFlow 庫,可能有 GPU 兼容問題
程式碼錯誤處理 需要補充異常處理 如果模型或圖片格式錯誤,程式可能會崩潰
TF.NET 維護狀況 活躍,但社群較小 官方支援有限,與 TensorFlow Python 相比資源較少

🔹 可能遇到的問題 & 解決方案

模型無法載入

問題: session.graph.Import(modelBytes); 可能會拋出錯誤
解法:

  • 確保 ssd_mobilenet_v2.pb 是正確的 TensorFlow 1.x frozen model
  • 嘗試 tf.saved_model.load() 方式載入

GPU 無法使用

問題: TensorFlow.NET 需要額外安裝 GPU 版的 TensorFlow
解法:

  • 安裝 SciSharp.TensorFlow.Redist-GPU 版本
    sh
    dotnet add package SciSharp.TensorFlow.Redist-GPU

物件偵測不準確

問題: 預訓練模型可能對特定場景效果不佳
解法:

  • 重新訓練模型(Transfer Learning),使用 自己的標註資料集
  • 可考慮 YOLOv5 或 EfficientDet,它們通常比 SSD 更準確

🚀 穩定運行的最佳建議

✅ 使用 TensorFlow 2.xSavedModel 格式,而非 Frozen Graph
✅ 在 Windows/Linux 進行測試,確保 CPU/GPU 驅動 兼容
✅ 若要高效能 物件偵測,可考慮 YOLO 或 Faster R-CNN
✅ 若專案需要長期維護,考慮 直接使用 Python TensorFlow API,社群支援更完整

結論: 🔹 TensorFlow.NET 適用於 .NET 環境物件偵測,但 相較於 Python TensorFlow,開發彈性較低
🔹 如果需求是長期專案,建議改用 Python API,或結合 .NET 與 Python 互操作 🚀

創作者介紹
創作者 IMM 的頭像
IMM-AT

IMM

IMM-AT 發表在 痞客邦 留言(0) 人氣( 17 )