テキストと画像の類似性
CLIP を使用して、Text-to-Image タスクで生成された画像と対応するプロンプトの間の類似性を計算します。インデックスが大きいほど、より良好になります。
from tqdm import tqdm
from PIL import Image
import torch
import os
import numpy as np
from transformers import CLIPProcessor, CLIPModel
model = CLIPModel.from_pretrained("clip-vit-base-patch16")
processor = CLIPProcessor.from_pretrained("clip-vit-base-patch16")
def get_clip_score(image_path,text):
image = Image.open(image_path)
inputs = processor(text=text, images=image, return_tensors="pt", padding=True)
outputs = model(**inputs)
print(outputs)
logits_per_image = outputs.logits_per_image
print(logits_per_image, logits_per_image.shape) # 1,4
return logits_per_image
例:
image_path='test.jpg'
text = ['dog','cat','pig'] # text must be a list
対応する出力スコアは、それぞれ と の類似性に[32.3232,52.2312,63.1298]
対応します。test.jpg
['dog','cat','pig']
事前トレーニング済みモデルをclip-vit-base-patch16
事前にダウンロードしてプロジェクト ディレクトリに配置する必要があることに注意してください。
ダウンロード可能なパスは次のとおりです: https://huggingface.co/openai/clip-vit-base-patch16/tree/main (1 つずつダウンロードする必要がある場合があります)
画像と画像の類似性
CLIP を使用して 2 つの画像間の類似度を計算します。SSIM、PSNR、MSE とは異なり、ここで計算される画像の類似度は画像の特徴レベルでの類似度ですが、SSIM、PSNR、MSE は主に撮像後のピクセル レベルでの類似度を比較します。
import torch
from transformers import CLIPImageProcessor, CLIPModel, CLIPTokenizer
# from transformers import CLIPProcessor, CLIPModel
from PIL import Image
import os
import cv2
# Load the CLIP model
model_ID = "clip-vit-base-patch16"
model = CLIPModel.from_pretrained(model_ID)
preprocess = CLIPImageProcessor.from_pretrained(model_ID)
# Define a function to load an image and preprocess it for CLIP
def load_and_preprocess_image(image_path):
# Load the image from the specified path
image = Image.open(image_path)
# Apply the CLIP preprocessing to the image
image = preprocess(image, return_tensors="pt")
# Return the preprocessed image
return image
def clip_img_score (img1_path,img2_path):
# Load the two images and preprocess them for CLIP
image_a = load_and_preprocess_image(img1_path)["pixel_values"]
image_b = load_and_preprocess_image(img2_path)["pixel_values"]
# Calculate the embeddings for the images using the CLIP model
with torch.no_grad():
embedding_a = model.get_image_features(image_a)
embedding_b = model.get_image_features(image_b)
# Calculate the cosine similarity between the embeddings
similarity_score = torch.nn.functional.cosine_similarity(embedding_a, embedding_b)
return similarity_score.item()
使用:
score = clip_img_score(img1_path,img1_path) #give the path to two images.
transformers
のバージョンは注目に値します。
ブロガーはpip install transformers==4.25.0
コードが正常に実行できることをテストしました。