金子邦彦研究室人工知能Windows で動く人工知能関係 Pythonアプリケーション,オープンソースソフトウエア)Recognize Anything のインストールと動作確認(ゼロショットの画像タグ付け)(Python,PyTorch を使用)(Windows 上)

Recognize Anything のインストールと動作確認(ゼロショットの画像タグ付け)(Python,PyTorch を使用)(Windows 上)

概要】 Recognize Anything Model(RAM)は,画像タグ付けのためのモデルであり,テキストのセマンティック解析によってラベルを取得する.RAMには6,449の一般的なラベルが含まれ,欠落したラベルを追加し,誤ったラベルをクリーニングする.OpenImages V6,COCO,ADE20kなどのデータセットで高い性能を示し,ゼロショット画像タグ付けも可能である.RecognizeAnythingのインストール(Windows上)には,ダウンロード,インストール,学習済みモデルのダウンロードを行う.Pythonプログラムを使用して画像ファイルやカメラから実行することができる.以上がRecognizeAnythingについての概要である

目次

  1. 前準備
  2. RecognizeAnything のインストール(Windows 上)
  3. RecognizeAnything の動作確認(Windows 上)
  4. RecognizeAnything を使う Python プログラムの実行(Windows 上)

Recognize Anything Model

画像タグ付けの学習は画像とテキストのペアを訓練データとして使用する。 Recognize Anything Model(RAM)は、画像タグ付けのためのモデルで、手動でのアノテーションではなく、テキストのセマンティック解析を自動化することでラベルを取得することを特徴とする。 Recognize Anything Model(RAM)のラベルシステムは、6,449の一般的なラベルを含んでいる。 また、データエンジンは、欠落しているラベルを追加し、誤ったラベルをクリーニングするために使用される。 データエンジンは既存のモデルを用いて追加のタグを生成し、画像内の特定のカテゴリに対応する領域を特定します。その後、同じカテゴリ内の領域を処理し、異常値を排除します。 さらに、Recognize Anything Model(RAM)は画像タグ付けとキャプションのタスクを統合し、その結果、ゼロショット画像タグ付けを可能にしている。これにより、未見のカテゴリについての処理が可能になる。また、学習のコストを抑制するために、Recognize Anything Model(RAM)はオープンソースでアノテーションフリーのデータセットを使用する。これらの特性により、Recognize Anything Model(RAM)はゼロショットの画像タグ付けだけでなく、学習済みモデルを用いた画像タグ付けでも高い性能を示すとされる。これは、OpenImages V6、COCO、ADE20kなどの一連のベンチマークデータセットでの評価により裏付けられている。

文献】 Recognize Anything: A Strong Image Tagging Model 6 Jun 2023 · Youcai Zhang, Xinyu Huang, Jinyu Ma, Zhaoyang Li, Zhaochuan Luo, Yanchun Xie, Yuzhuo Qin, Tong Luo, Yaqian Li, Shilong Liu, Yandong Guo, Lei Zhang ·

https://arxiv.org/pdf/2306.03514v3.pdf

関連する外部ページ

前準備

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

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

サイト内の関連ページ

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

関連する外部ページ

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

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

サイト内の関連ページ

関連する外部ページ

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

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

サイト内の関連ページ

NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバNVIDIA CUDA ツールキットNVIDIA cuDNN のインストールを行う.

関連する外部ページ

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

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

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

  2. PyTorch のページを確認

    PyTorch のページ: https://pytorch.org/index.html

  3. 次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドを使う).

    次のコマンドは, PyTorch 2.0 (NVIDIA CUDA 11.8 用) をインストールする. 但し,Anaconda3を使いたい場合には別手順になる.

    事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).

    PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.

    python -m pip install -U --ignore-installed pip
    python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118
    python -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    

    [image]

    Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt)管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).

    conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia
    py -c "import torch; print(torch.__version__, torch.cuda.is_available())" 
    

    サイト内の関連ページ

    関連する外部ページ

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

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

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

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

  2. ダウンロードとインストール

    cd %HOMEPATH%
    curl -O https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe
    .\rustup-init.exe
    

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

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

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

  2. ダウンロードとインストール,学習済みモデル ram_swin_large_14m.pth のダウンロード

    cd %HOMEPATH%
    rmdir /s /q recognize-anything
    git clone --recursive https://github.com/xinyu1205/recognize-anything
    cd recognize-anything
    python -m pip install -r requirements.txt
    mkdir pretrained
    cd pretrained
    curl -L -O  https://huggingface.co/spaces/xinyu1205/Recognize_Anything-Tag2Text/resolve/main/ram_swin_large_14m.pth
    

RecognizeAnything の動作確認(Windows 上)

動作確認を行う.公式ページの手順に従う.

Unseen Caterory の推論

  1. ファイル openset_utils.py を確認し,必要であれば,ファイルの中身を調整する
  2. 次のコマンドを実行

    cd %HOMEPATH%\recognize-anything
    echo RAM Inference on Unseen Categories (Open-Set)
    python inference_ram_openset.py  --image images/openset_example.jpg --pretrained pretrained/ram_swin_large_14m.pth
    

    [image]

推論

  1. ファイル openset_utils.py を確認し,調整する
  2. 次のコマンドを実行

    cd %HOMEPATH%\recognize-anything
    echo RAM Inference
    python inference_ram.py  --image images/1641173_2291260800.jpg --pretrained pretrained/ram_swin_large_14m.pth
    

    [image]

RecognizeAnything を使う Python プログラムの実行(Windows 上)

Unseen Caterory の推論

画像ファイル(複数可)での実行

実行時にファイルを選択する.ファイルは複数選択可能である.

  1. ファイル openset_utils.py を確認し,調整する
  2. Windows で,コマンドプロンプトを実行
  3. エディタを起動
    cd %HOMEPATH%\recognize-anything
    notepad a.py
    
  4. エディタで,次のプログラムを保存

    このプログラムは, 公式ページの GitHub のページ https://github.com/xinyu1205/recognize-anything/blob/main/inference_ram_openset.pyで公開されていたものを変更して使用している.

    '''
     * The Recognize Anything Model (RAM) inference on unseen classes
     * Written by Xinyu Huang
    '''
    import numpy as np
    import random
    
    import torch
    import torchvision.transforms as transforms
    
    from PIL import Image
    from ram.models import ram
    from ram import inference_ram_openset as inference
    
    from ram.utils import build_openset_label_embedding
    from torch import nn
    
    size = 384
    pretrained = 'pretrained/ram_swin_large_14m.pth'
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    transform = transforms.Compose([
        transforms.Resize((size, size)),
        transforms.ToTensor(), normalize
    ])
    
    model = ram(pretrained=pretrained, image_size=size, vit='swin_l')
    openset_label_embedding, openset_categories = build_openset_label_embedding()
    model.tag_list = np.array(openset_categories)
    model.label_embed = nn.Parameter(openset_label_embedding.float())
    
    model.num_class = len(openset_categories)
    # the threshold for unseen categories is often lower
    model.class_threshold = torch.ones(model.num_class) * 0.5
    
    model.eval()
    model = model.to(device)
    
    import tkinter as tk
    from tkinter import filedialog
    
    root = tk.Tk()
    root.withdraw()
    fpaths = filedialog.askopenfilenames()
    
    for fpath in root.tk.splitlist(fpaths):
        print("file name: ", fpath)
        raw_image = Image.open(fpath).convert("RGB").resize((size, size))
        image = transform(raw_image).unsqueeze(0).to(device)
        with torch.no_grad():
            tags = inference(image, model)
        print("Image Tags: ", tags)
    

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

    Python プログラムの実行

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

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

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

    python a.py
    

    ファイル選択画面が出るので,画像ファイルを選択する.ファイルは複数選択可能である.

    [image]
  6. 結果の確認

    [image]

パソコンのカメラで使用

  1. ファイル openset_utils.py を確認し,調整する
  2. Windows で,コマンドプロンプトを実行
  3. エディタを起動
    cd %HOMEPATH%\recognize-anything
    notepad b.py
    
  4. エディタで,次のプログラムを保存

    このプログラムは, 公式ページの GitHub のページ https://github.com/xinyu1205/recognize-anything/blob/main/inference_ram_openset.pyで公開されていたものを変更して使用している.

    '''
     * The Recognize Anything Model (RAM) inference on unseen classes
     * Written by Xinyu Huang
    '''
    import numpy as np
    import random
    
    import torch
    import torchvision.transforms as transforms
    
    from PIL import Image
    from ram.models import ram
    from ram import inference_ram_openset as inference
    
    from ram.utils import build_openset_label_embedding
    from torch import nn
    
    size = 384
    pretrained = 'pretrained/ram_swin_large_14m.pth'
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    transform = transforms.Compose([
        transforms.Resize((size, size)),
        transforms.ToTensor(), normalize
    ])
    
    model = ram(pretrained=pretrained, image_size=size, vit='swin_l')
    openset_label_embedding, openset_categories = build_openset_label_embedding()
    model.tag_list = np.array(openset_categories)
    model.label_embed = nn.Parameter(openset_label_embedding.float())
    
    model.num_class = len(openset_categories)
    # the threshold for unseen categories is often lower
    model.class_threshold = torch.ones(model.num_class) * 0.5
    
    model.eval()
    model = model.to(device)
    
    import cv2
    
    v = cv2.VideoCapture(0)
    while(v.isOpened()):
        r, f = v.read()
        if ( r == False ):
            break
        bgr_image = cv2.resize(f, (size, size))
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
        image = transform(Image.fromarray(rgb_image)).unsqueeze(0).to(device)
    
        tags = inference(image, model)
        cv2.imshow("", bgr_image)
        print("Image Tags: ", tags)
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    
  5. Python プログラムの実行
    python b.py
    
  6. 結果の確認

    [image]

    [image]

推論

画像ファイル(複数可)での実行

実行時にファイルを選択する.ファイルは複数選択可能である.

  1. Windows で,コマンドプロンプトを実行
  2. エディタを起動
    cd %HOMEPATH%\recognize-anything
    notepad c.py
    
  3. エディタで,次のプログラムを保存

    このプログラムは, 公式ページの GitHub のページ https://github.com/xinyu1205/recognize-anything/blob/main/inference_ram.pyで公開されていたものを変更して使用している.

    '''
     * The Recognize Anything Model (RAM)
     * Written by Xinyu Huang
    '''
    import numpy as np
    import random
    
    import torch
    import torchvision.transforms as transforms
    
    from PIL import Image
    from ram.models import ram
    from ram import inference_ram as inference
    
    size = 384
    pretrained = 'pretrained/ram_swin_large_14m.pth'
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    transform = transforms.Compose([
        transforms.Resize((size, size)),
        transforms.ToTensor(), normalize
    ])
    
    model = ram(pretrained=pretrained, image_size=size, vit='swin_l')
    model.eval()
    model = model.to(device)
    
    import tkinter as tk
    from tkinter import filedialog
    
    root = tk.Tk()
    root.withdraw()
    fpaths = filedialog.askopenfilenames()
    
    for fpath in root.tk.splitlist(fpaths):
        print("file name: ", fpath)
        raw_image = Image.open(fpath).convert("RGB").resize((size, size))
        image = transform(raw_image).unsqueeze(0).to(device)
        with torch.no_grad():
            tags = inference(image, model)
        print("Image Tags: ", tags[0])
    

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

    Python プログラムの実行

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

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

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

    python c.py
    

    ファイル選択画面が出るので,画像ファイルを選択する.ファイルは複数選択可能である.

    [image]
  5. 結果の確認

    [image]

パソコンのカメラで使用

  1. ファイル openset_utils.py を確認し,調整する
  2. Windows で,コマンドプロンプトを実行
  3. エディタを起動
    cd %HOMEPATH%\recognize-anything
    notepad d.py
    
  4. エディタで,次のプログラムを保存

    このプログラムは, 公式ページの GitHub のページ https://github.com/xinyu1205/recognize-anything/blob/main/inference_ram_openset.pyで公開されていたものを変更して使用している.

    '''
     * The Recognize Anything Model (RAM)
     * Written by Xinyu Huang
    '''
    import numpy as np
    import random
    
    import torch
    import torchvision.transforms as transforms
    
    from PIL import Image
    from ram.models import ram
    from ram import inference_ram as inference
    
    size = 384
    pretrained = 'pretrained/ram_swin_large_14m.pth'
    
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                     std=[0.229, 0.224, 0.225])
    transform = transforms.Compose([
        transforms.Resize((size, size)),
        transforms.ToTensor(), normalize
    ])
    
    model = ram(pretrained=pretrained, image_size=size, vit='swin_l')
    model.eval()
    model = model.to(device)
    
    import tkinter as tk
    from tkinter import filedialog
    
    import cv2
    
    v = cv2.VideoCapture(0)
    while(v.isOpened()):
        r, f = v.read()
        if ( r == False ):
            break
        bgr_image = cv2.resize(f, (size, size))
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)
        image = transform(Image.fromarray(rgb_image)).unsqueeze(0).to(device)
    
        tags = inference(image, model)
        cv2.imshow("", bgr_image)
        print("Image Tags: ", tags[0])
        # Press Q to exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    
    v.release()
    cv2.destroyAllWindows()
    
  5. Python プログラムの実行
    python d.py
    
  6. 結果の確認

    [image]

    [image]