Similitude texte-image
Utilisez CLIP pour calculer la similarité entre l'image générée dans la tâche Text-to-Image et l'invite correspondante. Plus l'index est grand, mieux c'est.
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
Exemple:
image_path='test.jpg'
text = ['dog','cat','pig'] # text must be a list
Les scores de sortie correspondants [32.3232,52.2312,63.1298]
correspondent test.jpg
à ['dog','cat','pig']
la similarité de et , respectivement.
Il convient de noter que le modèle pré-formé clip-vit-base-patch16
doit être téléchargé à l'avance et placé dans le répertoire du projet.
Voici un chemin téléchargeable : https://huggingface.co/openai/clip-vit-base-patch16/tree/main (vous devrez peut-être télécharger un par un)
Similitude image-image
Utilisez CLIP pour calculer la similarité entre deux images. Contrairement à SSIM, PSNR et MSE, la similarité d'image calculée ici est la similarité au niveau des caractéristiques de l'image, tandis que SSIM, PSNR et MSE comparent principalement le niveau de pixel après la similarité.
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()
utiliser:
score = clip_img_score(img1_path,img1_path) #give the path to two images.
Il est à noter que transformers
la version de .
Le blogueur a testé pip install transformers==4.25.0
que le code pouvait s'exécuter normalement.