金子邦彦研究室インストールWindows の種々のソフトウェア(インストール)GPU環境でのTensorFlow 2.10.1のインストールと活用(Windows 上)

GPU環境でのTensorFlow 2.10.1のインストールと活用(Windows 上)

要約

Windows環境でのTensorFlow 2.10.1のインストールから、行列計算や画像分類などのサンプルプログラムの実行までを説明している。TensorFlowのインストールに必要な前提条件として、Build Tools for Visual Studio 2022、Git、7-Zip、NVIDIA関連ソフトウェア(ドライバ、CUDAツールキット、cuDNN)のインストール方法も説明している。さらに、Pythonのインストールも示している。そして、TensorFlow 2.10.1のインストール手順と動作確認方法を詳述し、GPUが認識されているかの確認方法も提示している。最後に、TensorFlowを用いた行列の掛け算、主成分分析、特異値分解のプログラムとその実行方法を示し、加えて事前学習済みのConvNeXtBaseモデルを用いたリアルタイム画像分類および選択した画像の分類のプログラムとその実行方法も提示している。

目次

  1. 前準備
  2. TensorFlow 2.10.1のインストールと活用(Windows 上)
  3. 行列の掛け算,主成分分析,特異値分解(TensorFlow 2 のプログラム例)(Windows 上)
  4. ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類(TensorFlow, Keras を使用)

GPU

GPUは,グラフィックス・プロセッシング・ユニット(Graphics Processing Unit)の略である.3次元コンピュータグラフィックスや3次元ゲーム,動画編集,仮想通貨のマイニング,科学計算,ディープラーニングなど,並列処理が必要な幅広い分野で活用されている.

TensorFlow GPU 版

Tensorflowは,Google 社によりリリースされた強力な機械学習フレームワークである.Python,C/C++ 言語から利用することができ,CPU,GPU,TPU 上で動作する.TensorFlow の特徴の一つは,「データフローグラフ」という概念である.データフローグラフは,データの流れを定めるもので,グラフ内の節点はオペレーション(演算)であり,エッジは節点間を流れるデータ(テンソル)を表す.ここでいう「オペレーション(演算)」は,TensorFlow が提供する様々な処理の単位である.TensorFlow を使うことで,機械学習のアプリケーションをより簡単に作成することができるようになる.TensorFlow は,音声,画像、テキスト,ビデオなど,様々なタイプのデータを利用できる.TensorFlow は,2015年11月に最初のバージョンがリリースされた.

TensorFlow GPU 版の動作に必要なもの(2023年4月時点)

古いバージョンである2.4.4 あるいはそれ以前のバージョン のTensorFlow を使う場合は, 最新NVIDIA cuDNNを使わないこと. 詳しくは,別ページ »で説明

前準備

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

Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.

サイト内の関連ページ

Windows での Git のインストール: 別ページ »で説明している.

関連する外部ページ

Git の公式ページ: https://git-scm.com/

7-Zip のインストール

7-Zipは,ファイル圧縮・展開(解凍)ツール

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. 次のコマンドを実行

    次のコマンドは,7-Zip圧縮・展開(解凍)ツールをインストールするものである.

    winget install --scope machine 7zip.7zip
    powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\7-Zip\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
    

関連する外部ページ

関連項目7-Zip

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

サイト内の関連ページ

関連する外部ページ

Python の公式ページ: https://www.python.org/

Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット,NVIDIA cuDNN のインストール(Windows 上)

サイト内の関連ページ

Windows での Build Tools for Visual Studio 2022NVIDIA ドライバNVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.9.7 のインストールと動作確認: 別ページ »で説明している.

関連する外部ページ

TensorFlow 2.10.1のインストールと活用(Windows 上)

設定の要点

システム環境変数 TF_FORCE_GPU_ALLOW_GROWTH の設定: true

インストール手順

  1. Windows で,コマンドプロンプト管理者として実行

    コマンドプロンプトを管理者として実行: 別ページ »で説明

  2. 使用する Python のバージョンの確認
    python --version
    

    [image]
  3. pip と setuptools の更新

    ※ 「 python -m pip install ...」は,Python パッケージをインストールするためのコマンド.

    python -m pip install -U pip setuptools
    

    [image]
  4. TensorFlow, Keras 関係のパッケージのアンインストール操作

    トラブルの可能性を減らすために,関係のパッケージのアンインストールを行っておく.

    Windowspip を実行するときは,コマンドプロンプト管理者として開き,それを使って pip を実行することにする.

    python -m pip uninstall -y protobuf tensorflow tensorflow-cpu tensorflow-gpu tensorflow-intel tensorflow-text tensorflow-estimator tf-models-official tf_slim tensorflow_datasets tensorflow-hub keras keras-tuner keras-visualizer
    

    [image]
  5. TensorFlow 2.10.1 および関連パッケージ(tf_slim,tensorflow_datasets,tensorflow-hub,Keras,keras-tuner,keras-visualizer)のインストール.

    あわせて,TensorFlowの公式ドキュメント,サンプルコード、Kerasの追加モジュールもインストールする.

    pip を用いてインストールする.

    python -m pip install -U protobuf tensorflow==2.10.1 tf_slim tensorflow_datasets==4.8.3 tensorflow-hub keras keras-tuner keras-visualizer
    python -m pip install git+https://github.com/tensorflow/docs
    python -m pip install git+https://github.com/tensorflow/examples.git
    python -m pip install git+https://www.github.com/keras-team/keras-contrib.git
    

    [image]
    (以下省略)
  6. Pythonパッケージ(Pillow, pydot, matplotlib, seaborn, pandas, scipy, scikit-learn, scikit-learn-intelex, opencv-python, opencv-contrib-python)のインストール(インストール済みのときは最新版に更新)

    python -m pip install -U pillow pydot matplotlib seaborn pandas scipy scikit-learn scikit-learn-intelex opencv-python opencv-contrib-python
    
  7. Windowsシステム環境変数 TF_FORCE_GPU_ALLOW_GROWTH に,true を設定

    次のコマンドを実行

    powershell -command "[System.Environment]::SetEnvironmentVariable(\"TF_FORCE_GPU_ALLOW_GROWTH\", \"true\", \"Machine\")"
    

    [image]

動作確認

TensorFlow がインストールできたかを確認したい.

  1. Windows では,コマンドプロンプトを実行.
  2. TensorFlow のバージョン確認

    バージョン番号が表示されれば OK.下の図とは違うバージョンが表示されることがある.

    python -c "import tensorflow as tf; print( tf.__version__ )"
    

    [image]

    次のようなメッセージが出た場合には,メッセージに従い, NVIDIA ドライバNVIDIA CUDA ツールキットNVIDIA cuDNN のインストールを行う. 但し,GPU がない場合には,このメッセージを無視する.

    [image]
  3. TensorFlow パッケージの情報の表示

    pip show tensorflow
    

    [image]
  4. (GPU を使うとき) TensorFlow からGPU が認識できているかの確認

    TensorFlow が GPU を認識できているかの確認は,端末で,次を実行して行う.

    python -c "from tensorflow.python.client import device_lib; print(device_lib.list_local_devices())"
    

    実行結果の中に,次のように「device_type: "GPU"」があれば,GPUが認識できている.エラーメッセージが出ていないことを確認しておくこと.

    [image]

    ここで,GPU があるのに,TensorFlow から認識されていないかもしれない. TensorFlow GPU 版が指定するバージョンの NVIDIA CUDA ツールキットNVIDIA cuDNN がインストールされていないことが原因かも知れない.

    TensorFlow 2.5 の GPU 版での,cuDNN のバージョンは 8.2TensorFlow 2.4 の GPU 版での,cuDNN のバージョンは 8.0.5TensorFlow 2.3, 2.2, 2.1 の GPU 版での,cuDNN のバージョンは 7.6.そして,TensorFlow 1.13 以上 TensorFlow 2.0 までの GPU 版での,cuDNN のバージョンは7.4 が良いようである.

    Windows での NVIDIA ドライバNVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.9.7 のインストールと動作確認: 別ページ »で説明

行列の掛け算,主成分分析,特異値分解(TensorFlow 2 のプログラム例)(Windows 上)

行列の掛け算

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd %USERPROFILE%
    notepad matmul.py
    

    [image]
  3. エディタで,次のプログラムを保存

    このプログラムは,TensorFlowを使用してCPUとGPUでの行列積の計算時間を比較する. [5000, 10000, 15000, 20000] の異なる4通りのサイズの行列を2つ生成し,その行列積を求める.そのとき, 計算時間を測定して結果を表示する.

    import os
    import tensorflow as tf
    import time
    
    def measure_time(func):
        start_time = time.perf_counter()
        result = func()
        end_time = time.perf_counter()
        calculation_time = end_time - start_time
        return calculation_time
    
    def run_matmul(device_type, matrix_size):
        print(f'実行開始 - Matrix Size: {matrix_size}')
        print('device_type の設定:', device_type)
        
        with tf.device(device_type):
            X = tf.random.uniform((matrix_size, matrix_size), minval=0, maxval=1)
            Y = tf.random.uniform((matrix_size, matrix_size), minval=0, maxval=1)
            calculation_time = measure_time(lambda: tf.matmul(X, Y))
    
        physical_devices = tf.config.list_physical_devices()
        gpu_devices = tf.config.list_physical_devices('GPU')
        
        print(f"Running on {device_type}")
        print(f"Available devices: {physical_devices}")
        print(f"Calculation time: {calculation_time:.6f} seconds")
        print()
    
    # GPUの確認,GPUのメモリに関する設定
    def set_gpu_config():
        physical_devices = tf.config.list_physical_devices('GPU')
        if len(physical_devices) > 0:
            print("GPU available:", physical_devices)
            for device in physical_devices:
                tf.config.experimental.set_memory_growth(device, True)
        else:
            print("No GPU found. Running on CPU.")
    
    def main():
        set_gpu_config()
        # デバイス名の表示
        device_name = tf.config.list_logical_devices('GPU')
        print("Device name:", device_name)
    
        matrix_sizes = [5000, 10000, 15000, 20000]
        for size in matrix_sizes:
            print(f'Matrix Size: {size}')
            run_matmul('/GPU:0', size)
            run_matmul('/CPU:0', size)
            print('---')
    
    if __name__ == "__main__":
        main()
    

    [image]
  4. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    プログラムを matmul.pyのようなファイル名で保存したので, 「python matmul.py」のようなコマンドで行う.

    python matmul.py
    

    [image]
  5. 結果の確認

    [image]

主成分分析,特異値分解

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd %USERPROFILE%
    notepad pcasvd.py
    

    [image]
  3. エディタで,次のプログラムを保存

    このプログラムは,TensorFlowを使用して,行列に対してPCA(主成分分析)とSVD(特異値分解)の計算を行い,GPUとCPUでの実行時間を比較する. [1000, 2000, 3000, 4000] の異なる4通りのサイズの行列に対して, PCAとSVDの計算時間を測定し,結果を表示することで,GPUとCPUの性能の違いを確認できる.

    import os
    import tensorflow as tf
    import time
    
    def measure_time(func):
        start_time = time.perf_counter()
        result = func()
        end_time = time.perf_counter()
        calculation_time = end_time - start_time
        return calculation_time
    
    def run_pca_svd(device_type, matrix_size):
        print(f'実行開始 - Matrix Size: {matrix_size}')
        print('device_type の設定:', device_type)
        with tf.device(device_type):
            X = tf.random.uniform((matrix_size, matrix_size), minval=0, maxval=1)
            pca_time = measure_time(lambda: tf.linalg.eigh(tf.matmul(X, X, transpose_a=True)))
            svd_time = measure_time(lambda: tf.linalg.svd(X))
    
        physical_devices = tf.config.list_physical_devices()
        gpu_devices = tf.config.list_physical_devices('GPU')
        print(f"Running on {device_type}")
        print(f"Available devices: {physical_devices}")
        print(f"PCA calculation time: {pca_time:.6f} seconds")
        print(f"SVD calculation time: {svd_time:.6f} seconds")
        print()
    
    # GPUの確認,GPUのメモリに関する設定 
    def set_gpu_config():
        physical_devices = tf.config.list_physical_devices('GPU')
        if len(physical_devices) > 0:
            print("GPU available:", physical_devices)
            for device in physical_devices:
                tf.config.experimental.set_memory_growth(device, True)
        else:
            print("No GPU found. Running on CPU.")
    
    def main():
        set_gpu_config()
        # デバイス名の表示
        device_name = tf.config.list_logical_devices('GPU')
        print("Device name:", device_name)
    
        matrix_sizes = [1000, 2000, 3000, 4000]
        for size in matrix_sizes:
            print(f'Matrix Size: {size}')
            run_pca_svd('/GPU:0', size)
            run_pca_svd('/CPU:0', size)
            print('---')
    
    if __name__ == "__main__":
        main()
    

    [image]
  4. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    プログラムを pcasvd.pyのようなファイル名で保存したので, 「python pcasvd.py」のようなコマンドで行う.

    python pcasvd.py
    

    [image]
  5. 結果の確認

ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類(TensorFlow, Keras を使用)

パソコン接続のカメラを使用

ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類を行う.

  1. パソコン接続のカメラを使用するので準備しておく
  2. 前準備として Python 用 opencv-python のインストール

    python -m pip install -U opencv-python opencv-contrib-python
    
  3. Windows で,コマンドプロンプトを実行
  4. エディタを起動
    cd %USERPROFILE%
    notepad convnext.py
    
  5. エディタで,次のプログラムを保存

    このプログラムは,TensorFlow,ImageNet で学習済みのConvNeXtBaseモデルを活用し,カメラから取得した画像をリアルタイムで画像分類します.プログラムでは,GPUの設定,モデルのロード,フレームの前処理,画像分類,結果と推論に要した時間を表示します.カメラからの画像をリアルタイムで画像分類し,その結果をビジュアルに確認できるプログラムです.

    【説明】

    1. set_gpu_config()関数により、GPUの設定を行います。GPUが利用可能な場合は、使用可能なGPUデバイスを表示します。GPUが利用できない場合は、CPUを使用することを表示します。
    2. preprocess_image()関数により、入力画像の前処理を行います。前処理では、画像のリサイズ、色空間の変換、正規化を行います。
    3. load_model()関数により、ImageNetで学習済みのConvNeXtBaseモデルをロードします。
    4. classify_camera_frames()関数で、カメラからの画像を取得し、画像分類を行います。
      • 取得した画像をpreprocess_image()関数で前処理します。
      • 前処理された画像をモデルに入力し、分類を行います。
      • 分類結果から、最も確率の高いクラスの名前と信頼度を取得します。
      • 結果(クラス名、信頼度、推論時間、フレームレート)を画面上に描画します。
    5. main()関数で、GPUの設定を行い、モデルをロードし、classify_camera_frames()関数を呼び出してカメラからの画像の分類を開始します。
    6. 'q'キーが押されるまで、上記の処理を繰り返し行います。'q'キーが押されたら、プログラムを終了します。

    【使い方】

    1. 必要な準備

      プログラムを実行する前に、必要なライブラリ(TensorFlow、OpenCV、NumPy、urllib)がインストールされていることを確認してください。

    2. カメラの設定

      プログラムはデフォルトでカメラデバイス0を使用します。 異なるカメラを使用する場合は、cv2.VideoCapture(0)の引数を適切なデバイスIDに変更してください。

    3. モデルの選択

      プログラムはデフォルトでconvnext_baseモデルを使用します。 異なるTensorFlowのモデルを使用したい場合は、MODEL_NAMEの値を変更してください。 モデルによって入力サイズや前処理の要件が異なる場合があるため、注意が必要です。

    4. 前処理のパラメータ

      プログラムはデフォルトでMEANとSTDの値を使用して前処理を行います。 これらの値は、ImageNetデータセットで使用される一般的な値です。 モデルによっては別の値が適切な場合があります。

    5. GPUの使用

      プログラムは、利用可能な場合はGPUを使用します。 GPUが利用可能でない場合は、自動的にCPUにフォールバックします。

    6. プログラムの実行

      プログラムを実行すると、カメラからのリアルタイム画像分類が開始されます。 分類結果、信頼度、推論時間、フレームレートが画面上に表示されます。

    7. キー操作:

      'q'キーを押すとプログラムが終了します。 'p'キーを押すと、画像の分類を一時停止/再開できます。

    8. プログラムの終了:

      'q'キーを押すか、ウィンドウを閉じるとプログラムが終了します。

    以上の手順に従って、プログラムを実行してください。カメラからのリアルタイム画像分類を体験できます。

    import tensorflow as tf
    from tensorflow.keras.applications import ConvNeXtBase
    import numpy as np
    import time
    import cv2
    import json
    import urllib.request
    import os
    
    # ==== 設定 ====
    MODEL_NAME = 'convnext_base'
    INPUT_SIZE = (224, 224)
    MEAN = [0.485, 0.456, 0.406]
    STD = [0.229, 0.224, 0.225]
    FPS_BUFFER_SIZE = 10
    IMAGENET_LABELS_URL = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
    # =============
    
    def download_imagenet_labels(url: str, filename: str) -> None:
        if not os.path.exists(filename):
            print(f"Downloading {filename} from {url}")
            try:
                urllib.request.urlretrieve(url, filename)
                print(f"Downloaded {filename}")
            except Exception as e:
                print(f"Error downloading {filename}: {str(e)}")
                raise
        else:
            print(f"{filename} already exists.")
    
    # ImageNetのクラスラベルとクラス名のマッピングをダウンロード
    try:
        download_imagenet_labels(IMAGENET_LABELS_URL, 'imagenet_class_index.json')
    except Exception as e:
        print(f"Error downloading imagenet_class_index.json: {str(e)}")
        exit(1)
    
    # ImageNetのクラスラベルとクラス名のマッピングを読み込み
    try:
        with open('imagenet_class_index.json', 'r') as f:
            imagenet_labels = json.load(f)
    except Exception as e:
        print(f"Error loading imagenet_class_index.json: {str(e)}")
        exit(1)
    
    # GPUの設定と確認を行う関数
    def set_gpu_config():
        physical_devices = tf.config.list_physical_devices('GPU')
        if len(physical_devices) > 0:
            print("GPU available:", physical_devices)
            for device in physical_devices:
                tf.config.experimental.set_memory_growth(device, True)
        else:
            print("No GPU found. Running on CPU.")
    
    # モデルをロードする関数
    def load_model():
        model = ConvNeXtBase(weights='imagenet', input_shape=INPUT_SIZE+(3,))
        model.trainable = False
        return model
    
    # モデルの情報を表示する関数
    def print_model_info(model):
        print(f"Model: {MODEL_NAME}")
        print(f"Input image size: {INPUT_SIZE}")
        print(f"Number of classes: {len(imagenet_labels)}")
    
    # 画像の前処理を行う関数
    def preprocess_image(img):
        img = cv2.resize(img, INPUT_SIZE)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = img.astype(np.float32) / 255.0
        img = (img - MEAN) / STD
        img = np.expand_dims(img, axis=0)
        return img
    
    # 画像を分類する関数
    def classify_image(model, img):
        preds = model.predict(img)
        class_id = np.argmax(preds)
        class_name = imagenet_labels[class_id]
        confidence = preds[0][class_id]
        return class_name, confidence
    
    # フレームレートを更新する関数
    def update_fps(fps_buffer, prediction_time):
        fps_buffer.append(prediction_time)
        if len(fps_buffer) > FPS_BUFFER_SIZE:
            fps_buffer = fps_buffer[-FPS_BUFFER_SIZE:]
        fps = len(fps_buffer) / sum(fps_buffer)
        return fps
    
    # 結果を表示する関数
    def display_results(frame, class_name, confidence, prediction_time, fps):
        cv2.putText(frame, f"Class: {class_name}", (10, 30),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"Confidence: {confidence:.4f}", (10, 70),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"Time: {prediction_time:.4f} seconds", (10, 110),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
        cv2.putText(frame, f"FPS: {fps:.2f}", (10, 150),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    
    # カメラからのフレームを取得し、分類を行う関数
    def classify_camera_frames(model):
        cap = cv2.VideoCapture(0)
        fps_buffer = []
        paused = False
    
        while cap.isOpened():
            if not paused:
                ret, frame = cap.read()
                if not ret:
                    break
    
                img = preprocess_image(frame)
                start_time = time.perf_counter()
                class_name, confidence = classify_image(model, img)
                prediction_time = time.perf_counter() - start_time
                fps = update_fps(fps_buffer, prediction_time)
                display_results(frame, class_name, confidence, prediction_time, fps)
    
            cv2.imshow("Camera Classification", frame)
    
            key = cv2.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == ord('p'):
                paused = not paused
    
        cap.release()
        cv2.destroyAllWindows()
    
    def main():
        set_gpu_config()
        model = load_model()
        print_model_info(model)
        classify_camera_frames(model)
    
    if __name__ == '__main__':
        main()
    

    [image]
  6. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    プログラムを convnext.pyのようなファイル名で保存したので, 「python convnext.py」のようなコマンドで行う.

    python convnext.py
    

    [image]
  7. 結果の確認

    終了は q キー

    [image]

画像ファイルを選択

ImageNet で学習済みの ConvNeXtBase モデルを用いた画像分類を行う.

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd %USERPROFILE%
    notepad convnextimg.py
    

    [image]
  3. エディタで,次のプログラムを保存

    このプログラムは、TensorFlow、Keras、ConvNeXtBaseモデルを活用し、ユーザが選択した複数の画像について画像分類を行う。プログラムでは、GPUの設定、モデルのロード、画像の前処理、画像分類、結果と推論に要した時間を表示する。主な機能は以下の通りである。

    【説明】

    1. GPUの設定

      利用可能なGPUを確認し、GPUのメモリに関する設定を行う。GPUが見つからない場合はCPUで実行される。

    2. ConvNeXtBaseモデルのロード

      ImageNetで学習済みのConvNeXtBaseモデルをロードする。

    3. 画像ファイルの選択と分類

      ユーザーが複数の画像ファイルを選択し、選択された各画像に対して画像分類を実施する。分類結果と推論に要した時間を画像上に描画する。

    4. 結果の表示

      分類されたクラス名、信頼度、推論時間を画像上に重ねて表示する。

    5. 任意のキーを押すと次の画像に進み、全ての画像の分類が完了すると終了する。

    【使い方】

    1. 必要な準備

      プログラムを実行する前に、必要なライブラリ(TensorFlow、Keras、OpenCV、NumPy、urllib、tkinter)がインストールされていることを確認してください。

    2. モデルの選択

      プログラムはデフォルトでconvnext_baseモデルを使用します。 異なるKerasのモデルを使用したい場合は、MODEL_NAMEの値を変更してください。 モデルによって入力サイズや前処理の要件が異なる場合があるため、注意が必要です。

    3. 前処理のパラメータ

      プログラムはデフォルトでMEANとSTDの値を使用して前処理を行います。 これらの値は、ImageNetデータセットで使用される一般的な値です。 モデルによっては別の値が適切な場合があります。

    4. GPUの使用

      プログラムは、利用可能な場合はGPUを使用します。 GPUが利用可能でない場合は、自動的にCPUにフォールバックします。

    5. プログラムの実行

      プログラムを実行すると、画像ファイルの選択ダイアログが表示されます。 分類したい画像ファイルを複数選択し、「開く」をクリックしてください。

    import tensorflow as tf
    from tensorflow.keras.applications import ConvNeXtBase
    import numpy as np
    import time
    import cv2
    import json
    import urllib.request
    import os
    import tkinter as tk
    from tkinter import filedialog
    
    # ==== 設定 ====
    MODEL_NAME = 'convnext_base'
    INPUT_SIZE = (224, 224)
    MEAN = [0.485, 0.456, 0.406]
    STD = [0.229, 0.224, 0.225]
    IMAGENET_LABELS_URL = 'https://raw.githubusercontent.com/anishathalye/imagenet-simple-labels/master/imagenet-simple-labels.json'
    # =============
    
    def download_imagenet_labels(url: str, filename: str) -> None:
        if not os.path.exists(filename):
            print(f"Downloading {filename} from {url}")
            try:
                urllib.request.urlretrieve(url, filename)
                print(f"Downloaded {filename}")
            except Exception as e:
                print(f"Error downloading {filename}: {str(e)}")
                raise
        else:
            print(f"{filename} already exists.")
    
    # ImageNetのクラスラベルとクラス名のマッピングをダウンロード
    try:
        download_imagenet_labels(IMAGENET_LABELS_URL, 'imagenet_class_index.json')
    except Exception as e:
        print(f"Error downloading imagenet_class_index.json: {str(e)}")
        exit(1)
    
    # ImageNetのクラスラベルとクラス名のマッピングを読み込み
    try:
        with open('imagenet_class_index.json', 'r') as f:
            imagenet_labels = json.load(f)
    except Exception as e:
        print(f"Error loading imagenet_class_index.json: {str(e)}")
        exit(1)
    
    # GPUの設定と確認を行う関数
    def set_gpu_config():
        physical_devices = tf.config.list_physical_devices('GPU')
        if len(physical_devices) > 0:
            print("GPU available:", physical_devices)
            for device in physical_devices:
                tf.config.experimental.set_memory_growth(device, True)
        else:
            print("No GPU found. Running on CPU.")
    
    # モデルをロードする関数
    def load_model():
        model = ConvNeXtBase(weights='imagenet', input_shape=INPUT_SIZE+(3,))
        model.trainable = False
        return model
    
    # モデルの情報を表示する関数
    def print_model_info(model):
        print(f"Model: {MODEL_NAME}")
        print(f"Input image size: {INPUT_SIZE}")
        print(f"Number of classes: {len(imagenet_labels)}")
    
    # 画像の前処理を行う関数
    def preprocess_image(img):
        img = cv2.resize(img, INPUT_SIZE)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = img.astype(np.float32) / 255.0
        img = (img - MEAN) / STD
        img = np.expand_dims(img, axis=0)
        return img
    
    # 画像ファイルを選択する関数
    def select_files():
        try:
            if 'google.colab' in str(get_ipython()):
                from google.colab import files
                uploaded = files.upload()
                image_paths = list(uploaded.keys())
            else:
                root = tk.Tk()
                root.withdraw()
                image_paths = filedialog.askopenfilenames()
        except NameError:
            root = tk.Tk()
            root.withdraw()
            image_paths = filedialog.askopenfilenames()
        return image_paths
    
    # 選択した画像の分類を行う
    def classify_selected_images(model):
        image_paths = select_files()
        for image_path in image_paths:
            try:
                img = cv2.imread(image_path)
            except Exception as e:
                print(f"Error reading image {image_path}: {str(e)}")
                continue
            
            # 画像の前処理
            img_preprocessed = preprocess_image(img)
            
            # 画像の分類
            start_time = time.perf_counter()
            preds = model.predict(img_preprocessed)
            end_time = time.perf_counter()
            prediction_time = end_time - start_time
            
            top_pred_index = np.argmax(preds)
            class_name = imagenet_labels[top_pred_index]
            confidence = preds[0][top_pred_index]
            
            # 結果の表示
            cv2.putText(img, f"Class: {class_name}", (10, 30),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
            cv2.putText(img, f"Confidence: {confidence:.4f}", (10, 70),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
            cv2.putText(img, f"Time: {prediction_time:.4f} seconds", (10, 110),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
            
            cv2.imshow("Image Classification", img)
            cv2.waitKey(0)
        
        cv2.destroyAllWindows()
    
    def main():
        set_gpu_config()
        model = load_model()
        print_model_info(model)
        classify_selected_images(model)
    
    if __name__ == '__main__':
        main()
    

    [image]
  4. Python プログラムの実行

    Python プログラムの実行

    Python 開発環境(Jupyter Qt Console, Jupyter ノートブック (Jupyter Notebook), Jupyter Lab, Nteract, Spyder, PyCharm, PyScripterなど)も便利である.

    Python のまとめ: 別ページ »にまとめ

    プログラムを convnextimg.pyのようなファイル名で保存したので, 「python convnextimg.py」のようなコマンドで行う.

    python convnextimg.py
    

    [image]
  5. ファイルダイアログが開くので,画像ファイルを選ぶ.

    このとき,画像ファイルを複数選ぶことができる.

  6. 結果の確認

    画像分類の結果のクラス名,信頼度(Confidence),処理に要した時間が表示される.

    [image]

    [image]