CRAFT のインストールとテスト実行(テキスト検出)(Python,PyTorch を使用)(Windows 上)

概要

CRAFT(Character Region Awareness For Text detection)をインストールし,テキスト検出(text detection)を行う.

CRAFT

CRAFT は,文字領域(character region)と文字間のつながり(affinity)をそれぞれ推定し,その結果を統合することで,任意の形状のテキスト領域を検出する手法である.2019年発表.PyTorchによる公式実装が公開されており,学習済みモデルを用いてすぐにテキスト検出を試すことができる.

文献

Character Region Awareness for Text Detection, Baek, Youngmin and Lee, Bado and Han, Dongyoon and Yun, Sangdoo and Lee, Hwalsuk, Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition,2019.

https://arxiv.org/abs/1904.01941

関連する外部ページ

目次

前準備

Build Tools for Visual Studio 2026(ビルドツール)のインストール

Build Tools for Visual Studio 2026(ビルドツール)のインストールを行い、C/C++ コードのビルド環境を整える。

[Build Tools for Visual Studio 2026(ビルドツール)のインストール手順を見るには、ここをクリック]

Windows での Build Tools for Visual Studio 2026 のインストール

Build Tools for Visual Studio は,Visual Studio の IDE を含まない C/C++ コンパイラ,ライブラリ,ビルドツール等のコマンドライン向け開発ツールセットである。インストール済みの場合,この手順は不要である。

以下のコマンドは、Build Tools が未インストールの場合は winget で新規インストールし、インストール済みの場合は setup.exe modify でコンポーネントを追加する(バージョンは変更しない)。

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windows キーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

REM ============================================================
REM Visual C++ 再頒布可能パッケージ (VCRedist 2015-)
REM ============================================================
winget install --scope machine --id Microsoft.VCRedist.2015+.x64 -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/quiet /norestart"
if not "%ERRORLEVEL%"=="0" ( color 0c & echo VCRedist のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM ============================================================
REM Visual Studio Build Tools + Desktop development with C++
REM (VCTools、MSBuildTools、CMake連携、Clang、Windows 11 SDK)
REM ============================================================
REM 進行中のインストーラーを停止(ロック競合回避。対象プロセスが存在しない場合は
REM taskkillがエラーを返すが、これは想定内であるため出力のみ抑制する)
taskkill /F /IM vs_setup.exe /T >nul 2>&1
taskkill /F /IM vs_installer.exe /T >nul 2>&1
taskkill /F /IM vs_installerservice.exe /T >nul 2>&1
taskkill /F /IM msiexec.exe /T >nul 2>&1

REM Build Tools + Desktop development with C++(VCTools)+ 追加コンポーネント(一括)
REM 未インストール時: winget で新規インストール
REM インストール済み時: setup.exe modify でコンポーネント追加(バージョンは変更しない)
winget list --id Microsoft.VisualStudio.BuildTools 2>nul | findstr /i "BuildTools" >nul 2>&1
if %ERRORLEVEL% EQU 0 (
    for /f "usebackq delims=" %P in (`"C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do start /wait "" "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" modify --installPath "%P" --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64 --includeRecommended --quiet --norestart --nocache
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のコンポーネント追加に失敗しました & ping 127.0.0.1 -n 6 >nul & color )
) else (
    winget install --scope machine --id Microsoft.VisualStudio.BuildTools -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "--quiet --wait --norestart --nocache --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Workload.MSBuildTools --add Microsoft.VisualStudio.Component.VC.CMake.Project --add Microsoft.VisualStudio.Component.VC.Llvm.Clang --add Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --add Microsoft.VisualStudio.Component.VC.v143.x86.x64"
    if not "%ERRORLEVEL%"=="0" ( color 0c & echo Build Tools のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )
)

REM
REM BuildTools のインストールパスを vswhere.exe で取得(メジャーバージョンに依存しない)
set "VSWHERE=C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe"
set "BT_PATH="
for /f "usebackq delims=" %P in (`"%VSWHERE%" -products Microsoft.VisualStudio.Product.BuildTools -property installationPath`) do set "BT_PATH=%P"
if not defined BT_PATH ( color 0c & echo Build Tools のインストールパスを取得できませんでした & ping 127.0.0.1 -n 6 >nul & color )

REM 破損時の修復(任意、動作がおかしくなった場合)
REM if defined BT_PATH "C:\Program Files (x86)\Microsoft Visual Studio\Installer\setup.exe" repair --installPath "%BT_PATH%" --quiet --norestart
REM 導入確認(インストールパスが表示されれば正常)
"%VSWHERE%" -products * -requires Microsoft.VisualStudio.Workload.VCTools -property installationPath

上記のコマンドでは、Build Tools 本体と Visual C++ 再頒布可能パッケージをインストールし、続いて以下のコンポーネントを追加している。

追加のコンポーネントが必要になった場合は Visual Studio Installer で個別にインストールできる。

インストール完了の確認

winget list Microsoft.VisualStudio.BuildTools

Visual Studio を必要とするとき

Visual Studio の機能を必要とする場合は,追加インストールできる。

Python 3.12 のインストール

Pythonのインストールを行い、Pythonのプログラムを実行する環境を整える。扱う環境は、Windows搭載パソコンである。金子研究室では、Python 3.12.10を推奨する。

[Windows での Python 3.12 のインストール手順を見るには、ここをクリック]

Windows での Python 3.12 のインストール

以下のいずれかの方法でPython 3.12をインストールする。Pythonがインストール済みの場合、この手順は不要である。

方法 1:winget によるインストール

インストールコマンドの実行方法

管理者権限コマンドプロンプトを起動する(手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」)。そして、コマンド全体をコマンドプロンプトにコピー&ペーストする。

--scope machine を指定することで、システム全体(全ユーザー向け)にインストールされる。このオプションの実行には管理者権限が必要である。インストール完了後、コマンドプロンプトを再起動するとPATHが反映される。

REM Python 3.12 をシステム領域にインストール
winget install --id Python.Python.3.12 -e --scope machine --silent --accept-source-agreements --accept-package-agreements --override "/quiet InstallAllUsers=1 PrependPath=1 Include_test=0 Include_pip=1 Include_launcher=1 InstallLauncherAllUsers=1 TargetDir=\"C:\Program Files\Python312\""
if not "%ERRORLEVEL%"=="0" ( color 0c & echo Python 3.12 のインストールに失敗しました & ping 127.0.0.1 -n 6 >nul & color )

REM Python と Scripts を PATH 先頭に追加
powershell -NoProfile -Command "$p='C:\Program Files\Python312'; $s=\"$p\Scripts\"; if(Test-Path $p){$k=[Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment',$true); $c=$k.GetValue('Path','',[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames); $t=$k.GetValueKind('Path'); $new=$c; if((';'+$new+';') -notlike \"*;$p;*\"){$new=$p+';'+$new}; if((';'+$new+';') -notlike \"*;$s;*\"){$new=$s+';'+$new}; if($new -ne $c){$k.SetValue('Path',$new,$t)}; $k.Close()}"

REM 現在のセッションにも反映(システムPATHを再取得して連結)
for /f "usebackq tokens=2,*" %A in (`reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path`) do set "PATH=%B"

REM pip / wheel の更新
python -m pip install --no-user -U pip wheel
if not "%ERRORLEVEL%"=="0" ( color 0c & echo pip / wheel の更新に失敗しました & ping 127.0.0.1 -n 6 >nul & color )

方法 2:インストーラーによるインストール

  1. Python公式サイト(https://www.python.org/downloads/)にアクセスし、「Download Python 3.x.x」ボタンからWindows用インストーラーをダウンロードする。
  2. ダウンロードしたインストーラーを実行する。
  3. 初期画面の下部に表示される「Add python.exe to PATH」にチェックを入れてから「Customize installation」を選択する。このチェックを入れ忘れると、コマンドプロンプトから python コマンドを実行できない。
  4. 「Install Python 3.xx for all users」にチェックを入れ、「Install」をクリックする。

インストールの確認

コマンドプロンプトで以下を実行する。

python --version

バージョン番号(例:Python 3.12.x)が表示されればインストール成功である。「'python' は、内部コマンドまたは外部コマンドとして認識されていません。」と表示される場合は、インストールが正常に完了していない。

Git のインストール(Windows 上) [クリックして展開]

管理者権限コマンドプロンプトで以下を実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」).

REM Git をシステム領域にインストール
winget install --scope machine --id Git.Git -e --silent --disable-interactivity --force --accept-source-agreements --accept-package-agreements --override "/VERYSILENT /NORESTART /NOCANCEL /SP- /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS /COMPONENTS=""icons,ext\reg\shellhere,assoc,assoc_sh"" /o:PathOption=Cmd /o:CRLFOption=CRLFCommitAsIs /o:BashTerminalOption=MinTTY /o:DefaultBranchOption=main /o:EditorOption=VIM /o:SSHOption=OpenSSH /o:UseCredentialManager=Enabled /o:PerformanceTweaksFSCache=Enabled /o:EnableSymlinks=Disabled /o:EnableFSMonitor=Disabled"

NVIDIA ドライバのインストール(Windows 上)

NVIDIA ドライバとは

NVIDIA ドライバは,NVIDIA製GPUをWindowsシステム上で動作させるための基盤となるソフトウェアである.このドライバをインストールすることにより,GPUの性能を引き出し,グラフィックス処理やCUDAを利用したAI関連アプリケーションの計算速度が向上する.

ドライバは,NVIDIA公式サイトからダウンロードするか,NVIDIA GeForce Experienceソフトウェアを通じてインストール・更新する.

公式サイト: https://www.nvidia.co.jp/Download/index.aspx?lang=jp

サイト内の関連ページ

  1. (再掲) NVIDIA グラフィックス・ボードの確認

    インストールするドライバを選択するために,まず使用しているPCに搭載されているNVIDIAグラフィックス・ボードの種類を確認する(確認済みであれば,この手順は不要). Windows のコマンドプロンプトで次のコマンドを実行する.

    powershell -command "Get-CimInstance Win32_VideoController | Select-Object Name"
    
  2. NVIDIA ドライバのダウンロード

    確認したグラフィックス・ボードのモデル名と,使用しているWindowsのバージョンに対応するドライバを,以下のNVIDIA公式サイトからダウンロードする.

    https://www.nvidia.co.jp/Download/index.aspx?lang=jp

    サイトの指示に従い,製品タイプ,製品シリーズ,製品ファミリー,OS,言語などを選択して検索し,ドライバをダウンロードする.

  3. ドライバのインストール

    ダウンロードしたインストーラー(.exeファイル)を実行し,画面の指示に従ってインストールを進める.「カスタムインストール」を選択すると,インストールするコンポーネント(ドライバ本体,GeForce Experience,PhysXなど)を選ぶことができる.通常は「高速(推奨)」を選択する.

    インストール完了後,システムの再起動を求められる場合がある.

NVIDIA CUDA Toolkit 12.8のインストール

NVIDIA CUDA ツールキットの概要と注意点

NVIDIAのGPUを使用して並列計算を行うための開発・実行環境である.

主な機能: GPU を利用した並列処理のコンパイルと実行,GPU のメモリ管理,C++をベースとした拡張言語(CUDA C/C++)とAPI,ライブラリ(cuBLAS, cuFFTなど)を提供する.

関連する外部ページ

以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」).

REM NVIDIA CUDA Toolkit 12.8 をシステム領域にインストール
winget install --scope machine --id Nvidia.CUDA --version 12.8 -e --silent --disable-interactivity --force --uninstall-previous --accept-source-agreements --accept-package-agreements --override "-s -n"

REM 環境変数TEMP, TMPの設定(一時ファイルの保存先を短いパスに変更)
mkdir C:\TEMP
set "TEMP_PATH=C:\TEMP"
setx TEMP "%TEMP_PATH%" /M >nul
setx TMP "%TEMP_PATH%" /M >nul

注記:CRAFT は PyTorch 上で動作し,PyTorch の GPU 対応版パッケージには実行に必要な cuDNN のライブラリが同梱されているため,cuDNN を別途ダウンロードして手動で配置する作業は不要である.

PyTorch のインストール(Windows 上)

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」).
  2. PyTorch(CUDA 12.8 対応版)のインストール(Windows 上)

    次のコマンドを実行することにより,PyTorch(CUDA 12.8 対応版)およびPythonライブラリ(Pillow, matplotlib, seaborn, pandas, scipy, scikit-learn, scikit-learn-intelex, opencv-python, opencv-contrib-python)がインストール(インストール済みのときは最新版に更新)される.

    python -m pip install -U --no-user torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu128
    python -m pip install -U --no-user pillow matplotlib seaborn pandas scipy scikit-learn scikit-learn-intelex opencv-python opencv-contrib-python
    

CRAFT のインストールとテスト実行(Windows 上)

CRAFT のインストール(Windows 上)

  1. 以下の手順を管理者権限コマンドプロンプトで実行する (手順:Windowsキーまたはスタートメニュー → cmd と入力 → 右クリック → 「管理者として実行」).
  2. CRAFT のインストール

    craft-text-detector が要求する opencv-python の上限バージョン指定は古いため,--no-deps を付けて依存パッケージの自動インストールを抑止し,PyTorch と OpenCV は前段でインストール済みのバージョンをそのまま使用する.

    python -m pip install -U --no-user --no-deps craft-text-detector
    python -m pip install -U --no-user gdown scipy
    
  3. 画像ファイルを準備

    画像ファイル名は demo.png であるとする

  4. 動作確認のため,テキスト検出を行ってみる

    公式のプログラムを使用.run.py のようなファイル名で,任意のディレクトリに保存する.demo.png と同じディレクトリで実行すること.

    # run.py
    # CRAFT によるテキスト検出(画像ファイル入力)
    # 学習済みモデルは初回実行時に自動的にダウンロードされる
    #
    # pip install craft-text-detector
    
    from craft_text_detector import Craft
    
    IMAGE_PATH = "demo.png"
    OUTPUT_DIR = "outputs/"
    
    craft = Craft(output_dir=OUTPUT_DIR, crop_type="poly", cuda=True)
    prediction_result = craft.detect_text(IMAGE_PATH)
    
    craft.unload_craftnet_model()
    craft.unload_refinenet_model()
    
    cd /d c:%HOMEPATH%
    python run.py
    

    outputs ディレクトリに,検出されたテキスト領域を囲んだ画像(demo_text_detection.png),ヒートマップ画像,検出領域を切り出した画像が保存される.

パソコンのカメラで文字検出を行う(Windows 上)

  1. 次のプログラムを使用.run_camera.py のようなファイル名で保存
    # run_camera.py
    # CRAFT によるテキスト検出(パソコンのカメラ入力)
    #
    # pip install craft-text-detector opencv-python
    
    import cv2
    import numpy as np
    from craft_text_detector import (
        load_craftnet_model,
        load_refinenet_model,
        get_prediction,
        empty_cuda_cache,
    )
    
    craft_net = load_craftnet_model(cuda=True)
    refine_net = load_refinenet_model(cuda=True)
    
    v = cv2.VideoCapture(0)
    while v.isOpened():
        r, f = v.read()
        if r == False:
            break
    
        img = cv2.cvtColor(f, cv2.COLOR_BGR2RGB)
        prediction_result = get_prediction(
            image=img,
            craft_net=craft_net,
            refine_net=refine_net,
            text_threshold=0.7,
            link_threshold=0.4,
            low_text=0.4,
            cuda=True,
            long_size=1280,
        )
    
        boxes = [np.array(box, np.int32).reshape((-1, 1, 2)) for box in prediction_result["boxes"]]
        vis = cv2.polylines(f, boxes, True, (0, 0, 255), 2)
        cv2.imshow("CRAFT", vis)
    
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    empty_cuda_cache()
    
  2. 次のコマンドを実行
    cd /d c:%HOMEPATH%
    python run_camera.py