軽量Vision&Languageモデル(VLM)の「moondream2」を使ってみる

はじめに

Vision&Languageモデル(VLM)を使って写真の説明をしてもらいます。

今回は軽量モデルの「moondream2」を使ってみました。
huggingface.co

その他のVision&Languageモデル(VLM)

touch-sp.hatenablog.com
touch-sp.hatenablog.com
touch-sp.hatenablog.com

画像と結果

写真①


実行

python image2text.py -I image1.jpg -P "describe this image"

結果

In the image, two children are sitting on a rooftop, gazing up at a star-studded night sky. The child on the left is pointing upwards, their finger extended towards the sky, while the child on the right is looking up in awe. The sky is a deep purple, dotted with numerous stars, and a small white star is visible in the top left corner of the image.

DeepLで翻訳した結果

二人の子供が屋上に座り、満天の星空を見上げている。左側の子供は空に向かって指を伸ばし上方を指さしており、右側の子供は畏敬の念を抱いて見上げている。空は深い紫色で、無数の星が点在し、画像の左上には小さな白い星が見える。

実行

python image2text.py -I image1.jpg -P "How many children are sitting?"

結果

There are two children sitting next to each other.

写真②

ぱくたそからこちらの画像を使わせて頂きました。
www.pakutaso.com

実行

python image2text.py -I image2.jpg -P "describe this image"

結果

A young woman in a traditional Japanese kimono stands in a serene garden, holding a white fan with a gold handle. The kimono is adorned with a pink and white floral pattern, and the woman's face is lit up with a warm smile. The garden around her is lush with green trees and bushes, and a wooden structure can be seen in the background.

DeepLで翻訳した結果

日本の伝統的な着物を着た若い女性が、金の柄のついた白い扇子を手に、静謐な庭に立っている。着物にはピンクと白の花柄があしらわれ、女性の顔には温かい微笑みが浮かんでいる。彼女の周りの庭は木々や茂みの緑が生い茂り、背景には木造の建造物が見える。

Pythonスクリプト

最近「argparse」の代わりに「typer」を使っています。

from transformers import AutoModelForCausalLM, AutoTokenizer
from PIL import Image
from typer import Typer, Option

app = Typer()

@app.command()
def image2text(
    prompt: str=Option(..., "--prompt", "-P", help="prompt"),
    image_path: str=Option(..., "--image", "-I", help="path to a image")
):
    model_id = "vikhyatk/moondream2"
    revision = "main"
    model = AutoModelForCausalLM.from_pretrained(
        model_id,
        trust_remote_code=True,
        revision=revision
    )
    tokenizer = AutoTokenizer.from_pretrained(model_id, revision=revision)

    image = Image.open(image_path)
    enc_image = model.encode_image(image)
    print(model.answer_question(enc_image, prompt, tokenizer))

if __name__=="__main__":
    app()

PC環境

Windows 11
CUDA 11.8
Python 3.12

Python環境構築

pip install torch==2.2.2+cu118 torchvision==0.17.2+cu118 --index-url https://download.pytorch.org/whl/cu118
pip install transformers einops typer




このエントリーをはてなブックマークに追加