Posted on

TensorFlow 目標檢測API – 設定環境

相關教學資源

在Python安裝object_detection

我是在Windows的環境做開發,而官網的教學的環境是Linux,所以相關工具的安裝有花了一些時間,在這邊分享一下我的安裝方式

以下為Linux環境的工具安裝指令

sudo apt install -y protobuf-compiler
cd models/research/
protoc object_detection/protos/*.proto --python_out=.
cp object_detection/packages/tf2/setup.py .
python -m pip install .

大概就是要安裝protobuf,接著下載TensorFlows Model,然後把model放到你要呼叫Object Detection的程式目錄的下方 ,在這邊我執行python -m pip install .時,會一直出現如下錯誤

ERROR: Could not build wheels for opencv-python, which is required to install pyproject.toml-based projects

查了一下網路文章,大概猜到是python版本和opencv版本還有tensorflow版本有所不合,所以到官方網站看一下安裝所需要的環境需求如下,不同版本的Tensorflow所要搭配使用的OpenCV、Python的版本都不同:

最後我是使用python3.7的環境,才成功的安裝好object_detection

conda create -n object_detection python=3.7.16
conda activate object_detection
cd models/research/
python -m pip install .

安裝protobuf工具

在 Windows 上,可以通過以下步驟安裝 protobuf 編譯器:

  • 下載安裝包: 訪問 protobuf 的 GitHub Release 頁面(https://github.com/protocolbuffers/protobuf/releases),找到適用於 Windows 的預編譯二進製文件(例如 protoc-3.x.x-win64.zip)並下載到本地。
  • 解壓縮文件: 將下載的 zip 文件解壓縮到你想要安裝的位置,例如解壓縮到 C:\protobuf 文件夾。
  • 設置環境變量: 將解壓縮後的 bin 文件夾路徑添加到系統的環境變量中,這樣系統就能在任意位置找到 protoc 命令。
  • 驗證安裝: 打開命令提示符視窗,運行protoc --version,檢查 protoc 是否成功安裝。

安裝完成之後,就可以在./models/research下面執行

protoc object_detection/protos/*.proto --python_out=.

接著就可以用下面指令進行測試

python object_detection/builders/model_builder_tf2_test.py

如果沒有把*.proto編譯成.py,在執行物件偵測的程式碼時會出現以下錯誤

from object_detection.protos import string_int_label_map_pb2

ImportError: cannot import name ‘string_int_label_map_pb2

其他遇到的錯誤

DLL載入錯誤

import _ssl # if we can’t import it, let the error propagate

ImportError: DLL load failed: The specified module could not be found.

討論串: Python 3.7 anaconda environment – import _ssl DLL load fail error

解法: From anaconda3\Library\bin copy below files and paste them in anaconda3/DLLs:

setup.cfg指令過期錯誤

site-packages\setuptools\config\setupcfg.py:293: _DeprecatedConfig: Deprecated config in `setup.cfg`

AttributeError: module ‘os’ has no attribute ‘add_dll_directory’

解法: python環境和套件之間版本不合,重新檢查套件版本是否符合官網要求

以下為我最終使用的環境的套件版本清單: