使用 TensorFlow.js 進行人臉偵測

本指南介紹 TensorFlow.js 與 Docker 的無縫整合,以執行人臉偵測。在本指南中,您將探索如何

  • 使用 Docker 運行容器化的 TensorFlow.js 應用程式。
  • 使用 TensorFlow.js 在網頁應用程式中實作人臉偵測。
  • 為 TensorFlow.js 網頁應用程式構建 Dockerfile。
  • 使用 Docker Compose 進行即時應用程式開發和更新。
  • 在 Docker Hub 上分享您的 Docker 映像檔,以促進部署並擴大觸及範圍。

致謝

Docker 要感謝 Harsh Manvar 對本指南的貢獻。

先決條件

  • 您已安裝最新版本的 Docker Desktop
  • 您有一個 Git 用戶端。本指南中的範例使用基於命令列的 Git 用戶端,但您可以使用任何用戶端。

什麼是 TensorFlow.js?

TensorFlow.js 是一個開源 JavaScript 機器學習函式庫,可讓您在瀏覽器或 Node.js 上訓練和部署機器學習模型。它支援從頭開始建立新模型或使用預先訓練的模型,直接在網路環境中促進各種機器學習應用程式。TensorFlow.js 提供高效能的運算,讓沒有深度機器學習專業知識的網頁開發人員也能使用複雜的機器學習任務。

為什麼要一起使用 TensorFlow.js 和 Docker?

  • 環境一致性和簡化的部署:Docker 將 TensorFlow.js 應用程式及其依賴項打包到容器中,確保在所有環境中一致地運行,並簡化部署。
  • 高效的開發和輕鬆擴展:Docker 使用熱重載等功能提高開發效率,並使用 Kubernetes 等協調工具方便 TensorFlow.js 應用程式的擴展。
  • 隔離和增強安全性:Docker 將 TensorFlow.js 應用程式隔離在安全的環境中,最大限度地減少衝突和安全漏洞,同時以有限的權限運行應用程式。

取得並運行範例應用程式

在終端機中,使用以下命令複製範例應用程式。

$ git clone https://github.com/harsh4870/TensorJS-Face-Detection

複製應用程式後,您會注意到應用程式有一個 `Dockerfile`。這個 Dockerfile 讓您只需使用 Docker 即可在本地構建和運行應用程式。

在將應用程式作為容器運行之前,您必須將其構建成映像檔。在 `TensorJS-Face-Detection` 目錄中運行以下命令,以構建名為 `face-detection-tensorjs` 的映像檔。

$ docker build -t face-detection-tensorjs .

此命令會將應用程式建置成映像檔。根據您的網路連線速度,第一次執行此命令時,下載必要的組件可能需要幾分鐘的時間。

若要將映像檔作為容器執行,請在終端機中執行下列命令。

$ docker run -p 80:80 face-detection-tensorjs

此命令會執行容器,並將容器中的連接埠 80 對應到系統上的連接埠 80。

應用程式執行後,請開啟網頁瀏覽器並在 http://localhost:80 存取應用程式。您可能需要授予應用程式存取您網路攝影機的權限。

在網路應用程式中,您可以將後端更改為使用下列其中一項

  • WASM
  • WebGL
  • CPU

若要停止應用程式,請在終端機中按下 ctrl+c

關於應用程式

此範例應用程式使用 MediaPipeWASM

WebAssembly (WASM) 是一種低階、類似組合語言的語言,具有緊湊的二進位格式,可以在網頁瀏覽器中以接近原生速度執行。它允許將以 C/C++ 等語言編寫的程式碼編譯成可以在瀏覽器中執行的二進位檔。

當需要高效能,且 WebGL 後端不支援或您希望在所有裝置上獲得一致的效能而不依賴 GPU 時,WASM 是一個不錯的選擇。

WebGL

WebGL 是一種瀏覽器 API,允許 GPU 加速使用物理和影像處理及效果作為網頁畫布的一部分。

WebGL 非常適合可平行化且可以從 GPU 加速中顯著受益的運算,例如深度學習模型中常見的矩陣乘法和卷積。

CPU

CPU 後端使用純 JavaScript 執行,利用裝置的中央處理器 (CPU)。此後端具有最廣泛的相容性,並在 WebGL 和 WASM 後端都不可用或不適合時充當備用方案。

瀏覽應用程式的程式碼

在以下章節中探索每個檔案的用途及其內容。

index.html 檔案

index.html 檔案作為網路應用程式的前端,利用 TensorFlow.js 從網路攝影機視訊畫面進行即時人臉偵測。它整合了多種技術和函式庫,以便直接在瀏覽器中進行機器學習。它使用多個 TensorFlow.js 函式庫,包括

  • tfjs-core 和 tfjs-converter,用於核心 TensorFlow.js 功能和模型轉換。
  • tfjs-backend-webgl、tfjs-backend-cpu 和 tf-backend-wasm 腳本,用於 TensorFlow.js 可以使用的不同計算後端選項。這些後端允許應用程式利用使用者的硬體功能高效地執行機器學習任務。
  • BlazeFace 函式庫,一個用於人臉偵測的 TensorFlow 模型。

它還使用以下額外的函式庫

  • dat.GUI,用於建立圖形介面以即時與應用程式的設定互動,例如在 TensorFlow.js 後端之間切換。
  • Stats.min.js,用於顯示效能指標(如 FPS)以監控應用程式在運作期間的效率。
<style>
  body {
    margin: 25px;
  }

  .true {
    color: green;
  }

  .false {
    color: red;
  }

  #main {
    position: relative;
    margin: 50px 0;
  }

  canvas {
    position: absolute;
    top: 0;
    left: 0;
  }

  #description {
    margin-top: 20px;
    width: 600px;
  }

  #description-title {
    font-weight: bold;
    font-size: 18px;
  }
</style>

<body>
  <div id="main">
    <video
      id="video"
      playsinline
      style="
      -webkit-transform: scaleX(-1);
      transform: scaleX(-1);
      width: auto;
      height: auto;
      "
    ></video>
    <canvas id="output"></canvas>
    <video
      id="video"
      playsinline
      style="
      -webkit-transform: scaleX(-1);
      transform: scaleX(-1);
      visibility: hidden;
      width: auto;
      height: auto;
      "
    ></video>
  </div>
</body>
<script src="https://unpkg.com/@tensorflow/tfjs-core@2.1.0/dist/tf-core.js"></script>
<script src="https://unpkg.com/@tensorflow/tfjs-converter@2.1.0/dist/tf-converter.js"></script>

<script src="https://unpkg.com/@tensorflow/tfjs-backend-webgl@2.1.0/dist/tf-backend-webgl.js"></script>
<script src="https://unpkg.com/@tensorflow/tfjs-backend-cpu@2.1.0/dist/tf-backend-cpu.js"></script>
<script src="./tf-backend-wasm.js"></script>

<script src="https://unpkg.com/@tensorflow-models/blazeface@0.0.5/dist/blazeface.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stats.js/r16/Stats.min.js"></script>
<script src="./index.js"></script>

index.js 檔案

index.js 檔案執行人臉偵測邏輯。它展示了網路開發和機器學習整合中的幾個進階概念。以下是其一些關鍵組件和功能的細分

  • Stats.js:腳本首先建立一個 Stats 實例,以即時監控和顯示應用程式的畫面播放速率 (FPS)。這有助於效能分析,尤其是在測試不同 TensorFlow.js 後端對應用程式速度的影響時。
  • TensorFlow.js:應用程式允許使用者透過 dat.GUI 提供的圖形介面在 TensorFlow.js 的不同計算後端(wasm、webgl 和 cpu)之間切換。更改後端可能會影響效能和相容性,具體取決於裝置和瀏覽器。addFlagLabels 函式會動態檢查和顯示是否支援 SIMD(單指令多資料)和多執行緒,這與 wasm 後端的效能最佳化相關。
  • setupCamera 函式:使用 MediaDevices Web API 初始化使用者的網路攝影機。它將視訊串流設定為不包含音訊並使用前置鏡頭(facingMode: 'user')。載入視訊中資料後,它會使用視訊元素解析一個 promise,然後將其用於人臉偵測。
  • BlazeFace:此應用程式的核心是 renderPrediction 函式,它使用 BlazeFace 模型(一種用於偵測影像中人臉的輕量級模型)執行即時人臉偵測。該函式在每個動畫影格上呼叫 model.estimateFaces 以從視訊畫面中偵測人臉。對於每個偵測到的人臉,它會在覆蓋視訊的畫布上繪製一個紅色矩形框住人臉,並繪製藍點表示臉部特徵點。
const stats = new Stats();
stats.showPanel(0);
document.body.prepend(stats.domElement);

let model, ctx, videoWidth, videoHeight, video, canvas;

const state = {
  backend: "wasm",
};

const gui = new dat.GUI();
gui
  .add(state, "backend", ["wasm", "webgl", "cpu"])
  .onChange(async (backend) => {
    await tf.setBackend(backend);
    addFlagLables();
  });

async function addFlagLables() {
  if (!document.querySelector("#simd_supported")) {
    const simdSupportLabel = document.createElement("div");
    simdSupportLabel.id = "simd_supported";
    simdSupportLabel.style = "font-weight: bold";
    const simdSupported = await tf.env().getAsync("WASM_HAS_SIMD_SUPPORT");
    simdSupportLabel.innerHTML = `SIMD supported: <span class=${simdSupported}>${simdSupported}<span>`;
    document.querySelector("#description").appendChild(simdSupportLabel);
  }

  if (!document.querySelector("#threads_supported")) {
    const threadSupportLabel = document.createElement("div");
    threadSupportLabel.id = "threads_supported";
    threadSupportLabel.style = "font-weight: bold";
    const threadsSupported = await tf
      .env()
      .getAsync("WASM_HAS_MULTITHREAD_SUPPORT");
    threadSupportLabel.innerHTML = `Threads supported: <span class=${threadsSupported}>${threadsSupported}</span>`;
    document.querySelector("#description").appendChild(threadSupportLabel);
  }
}

async function setupCamera() {
  video = document.getElementById("video");

  const stream = await navigator.mediaDevices.getUserMedia({
    audio: false,
    video: { facingMode: "user" },
  });
  video.srcObject = stream;

  return new Promise((resolve) => {
    video.onloadedmetadata = () => {
      resolve(video);
    };
  });
}

const renderPrediction = async () => {
  stats.begin();

  const returnTensors = false;
  const flipHorizontal = true;
  const annotateBoxes = true;
  const predictions = await model.estimateFaces(
    video,
    returnTensors,
    flipHorizontal,
    annotateBoxes,
  );

  if (predictions.length > 0) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (let i = 0; i < predictions.length; i++) {
      if (returnTensors) {
        predictions[i].topLeft = predictions[i].topLeft.arraySync();
        predictions[i].bottomRight = predictions[i].bottomRight.arraySync();
        if (annotateBoxes) {
          predictions[i].landmarks = predictions[i].landmarks.arraySync();
        }
      }

      const start = predictions[i].topLeft;
      const end = predictions[i].bottomRight;
      const size = [end[0] - start[0], end[1] - start[1]];
      ctx.fillStyle = "rgba(255, 0, 0, 0.5)";
      ctx.fillRect(start[0], start[1], size[0], size[1]);

      if (annotateBoxes) {
        const landmarks = predictions[i].landmarks;

        ctx.fillStyle = "blue";
        for (let j = 0; j < landmarks.length; j++) {
          const x = landmarks[j][0];
          const y = landmarks[j][1];
          ctx.fillRect(x, y, 5, 5);
        }
      }
    }
  }

  stats.end();

  requestAnimationFrame(renderPrediction);
};

const setupPage = async () => {
  await tf.setBackend(state.backend);
  addFlagLables();
  await setupCamera();
  video.play();

  videoWidth = video.videoWidth;
  videoHeight = video.videoHeight;
  video.width = videoWidth;
  video.height = videoHeight;

  canvas = document.getElementById("output");
  canvas.width = videoWidth;
  canvas.height = videoHeight;
  ctx = canvas.getContext("2d");
  ctx.fillStyle = "rgba(255, 0, 0, 0.5)";

  model = await blazeface.load();

  renderPrediction();
};

setupPage();

tf-backend-wasm.js 檔案

tf-backend-wasm.js 檔案是 TensorFlow.js 函式庫tfjs-backend-wasm-simd.wasm 檔案

tfjs-backend-wasm-simd.wasm 檔案是 TensorFlow.js 函式庫瀏覽 Dockerfile

在基於 Docker 的專案中,Dockerfile 作為建置應用程式環境的基礎資源。

Dockerfile 是一個文字檔,用於指示 Docker 如何建立應用程式環境的映像檔。映像檔包含執行應用程式所需的一切,例如檔案、套件和工具。

以下是這個專案的 Dockerfile。

此 Dockerfile 定義了一個映像檔,使用 Nginx 從 Alpine Linux 基礎映像檔提供靜態內容。

使用 Compose 進行開發

Docker Compose 是一個用於定義和執行多容器 Docker 應用程式的工具。使用 Compose,您可以使用 YAML 檔案來配置應用程式的服務、網路和磁碟區。在這種情況下,應用程式不是多容器應用程式,但 Docker Compose 具有其他有用的開發功能,例如 Compose 檔案監控

範例應用程式尚未有 Compose 檔案。要建立 Compose 檔案,請在 TensorJS-Face-Detection 目錄中建立一個名為 compose.yaml 的文字檔,然後新增以下內容。

services:
  server:
    build:
      context: .
    ports:
      - 80:80
    develop:
      watch:
        - action: sync
          path: .
          target: /usr/share/nginx/html

此 Compose 檔案定義了一個使用相同目錄中的 Dockerfile 建置的服務。它將主機上的埠 80 映射到容器中的埠 80。它還有一個帶有 watch 屬性的 develop 子區段,該屬性定義了一系列規則,用於根據本地檔案變更控制自動服務更新。有關 Compose 指令的更多詳細資訊,請參閱 Compose 檔案參考

儲存對 compose.yaml 檔案的變更,然後執行以下命令來執行應用程式。

$ docker compose watch

應用程式執行後,請開啟網頁瀏覽器並在 http://localhost:80 存取應用程式。您可能需要授予應用程式存取您網路攝影機的權限。

現在,您可以更改程式碼,並看到變更自動反映在容器中,而無需重建和重新執行容器。

開啟 index.js 檔案,並在第 83 行將地標點的顏色從藍色更新為綠色。

-        ctx.fillStyle = "blue";
+        ctx.fillStyle = "green";

儲存對 index.js 檔案的變更,然後重新整理瀏覽器頁面。地標點現在應該顯示為綠色。

若要停止應用程式,請在終端機中按下 ctrl+c

分享您的映像檔

將您的 Docker 映像檔發佈到 Docker Hub 可以簡化其他人的部署流程,使其能夠無縫整合到各種專案中。它還能促進您容器化解決方案的採用,擴大其在開發者生態系統中的影響力。要分享您的映像檔

  1. 註冊 或登入 Docker Hub

  • 執行以下 docker push 命令將映像檔推送到 Docker Hub。將 YOUR-USER-NAME 替換為您的 Docker ID。

  • 確認您已將映像檔推送到 Docker Hub。

    1. 前往 Docker Hub
      $ docker run -p 80:80 YOUR-USER-NAME/face-detection-tensorjs
      
  • 總結

    本指南示範了如何利用 TensorFlow.js 和 Docker 在 Web 應用程式中進行人臉偵測。它突出了執行容器化 TensorFlow.js 應用程式的簡便性,以及使用 Docker Compose 進行即時程式碼變更的開發。此外,它還涵蓋了如何在 Docker Hub 上分享您的 Docker 映像檔,以簡化其他人的部署,並增強應用程式在開發者社群中的影響力。

    相關資訊