File size: 1,707 Bytes
fca5410
 
 
 
 
d3172ff
 
 
fca5410
d3172ff
 
 
fca5410
 
 
 
 
 
 
 
 
 
 
 
 
d3172ff
fca5410
 
 
 
 
d3172ff
fca5410
 
 
d3172ff
fca5410
 
 
 
 
d3172ff
fca5410
 
 
 
 
 
d3172ff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import torch
import torchvision.transforms as transforms
from PIL import Image
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
from torchvision.models import resnet50
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader

# Load a pre-trained ResNet-50 model
model = resnet50(pretrained=True)
model.eval()

# Define a function to preprocess images
def preprocess_image(image_path):
    transform = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
    ])
    image = Image.open(image_path)
    image = transform(image).unsqueeze(0)  # Add a batch dimension
    return image

# Load your ideal subset of images
ideal_image_paths = ["/content/trunck.jpg", "t4.jpg"]  # Replace with your ideal image file paths
ideal_embeddings = []

for image_path in ideal_image_paths:
    image = preprocess_image(image_path)
    with torch.no_grad():
        embedding = model(image).squeeze().numpy()
        ideal_embeddings.append(embedding)

# Load a set of candidate images
candidate_image_paths = ["/content/trunck2.jpg", "t3.jpg", "car.jpg",]  # Replace with your candidate image file paths
candidate_embeddings = []

for image_path in candidate_image_paths:
    image = preprocess_image(image_path)
    with torch.no_grad():
        embedding = model(image).squeeze().numpy()
        candidate_embeddings.append(embedding)

# Calculate similarities between ideal and candidate images using cosine similarity
similarities = cosine_similarity(ideal_embeddings, candidate_embeddings)

# Print the similarity matrix
print(similarities)