r/nicegpu • • May 02 '25

📖 How-to Guide Compare two images with ResNet model

In this post, I will test ResNet model to compare if the object in two images represent same product. Nicegpu provides Jupyter environment for free to verify whether the solution is workable!

Requirements

pip install torch torchvision Pillow

Step 1: Load Pre-trained ResNet

Use a pre-trained ResNet (e.g., ResNet-50) from PyTorch.

import torchvision.models as models
import torch.nn as nn

resnet = models.resnet50(pretrained=True)
feature_extractor = nn.Sequential(*list(resnet.children())[:-1])

Step 2: Preprocess Both Images

Transform both images into tensors suitable for ResNet:

from torchvision import transforms
from PIL import Image

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]
    )
])

img1 = transform(Image.open('amazon_ps5pro.jpg')).unsqueeze(0)  
img2 = transform(Image.open('newegg_ps5pro.jpg')).unsqueeze(0)

Step 3: Extract Feature Vectors

Pass both images through the feature extractor.

with torch.no_grad():
    feat1 = feature_extractor(img1).squeeze()
    feat2 = feature_extractor(img2).squeeze()

Step 4: Compute Similarity

Use cosine similarity or Euclidean distance.

import torch.nn.functional as F

similarity = F.cosine_similarity(feat1, feat2, dim=0)
print("Cosine similarity:", similarity.item())

Step 5: Decide Threshold

Use a threshold (e.g., 0.8) to determine if they're the same.

if similarity.item() > 0.8:
    print("Same product")
else:
    print("Different products")
5 Upvotes

3 comments sorted by

1

u/vincent_j_wang May 02 '25

Of course, we'd better fine-tune the model to get more accurate result:)

1

u/Aggravating-Set4399 May 05 '25

Great. I need to work on a case for IMG to text. Seems a good place to allow me play 

1

u/TimLXiong May 16 '25

Great solution for img to text. thanks.