|
| 1 | +import torch |
| 2 | +import torch.nn.functional as F |
| 3 | +from torchvision.transforms import ToTensor |
| 4 | +from PIL import Image |
| 5 | +from torchvision.models import vgg16 |
| 6 | +import torchvision.transforms as transforms |
| 7 | + |
| 8 | +# Upoading reference and target image |
| 9 | +reference_image = Image.open('ref1-0.jpg').convert('RGB') |
| 10 | +target_image = Image.open('tar2-0.jpg').convert('RGB') |
| 11 | + |
| 12 | +# Converting images to Tensor format |
| 13 | +reference_tensor = ToTensor()(reference_image) |
| 14 | +target_tensor = ToTensor()(target_image) |
| 15 | + |
| 16 | +# Check the size of the images and resize them if necessary |
| 17 | +if reference_tensor.dim() != 3 or target_tensor.dim() != 3: |
| 18 | + print("Image sizes are mismatched. Use RGB images.") |
| 19 | + exit() |
| 20 | + |
| 21 | +if reference_tensor.shape != target_tensor.shape: |
| 22 | + print("Reference and target images must be equal in size.") |
| 23 | + exit() |
| 24 | + |
| 25 | +# Reshape dimensions |
| 26 | +reference_tensor = reference_tensor.unsqueeze(0) # Add batch size |
| 27 | +target_tensor = target_tensor.unsqueeze(0) |
| 28 | + |
| 29 | +# Moving image tensors to the GPU |
| 30 | +device = torch.device("cuda" if torch.cuda.is_available() else "cpu") |
| 31 | +reference_tensor = reference_tensor.to(device) |
| 32 | +target_tensor = target_tensor.to(device) |
| 33 | + |
| 34 | +# Loading the VGG16 model |
| 35 | +model = vgg16(pretrained=True) |
| 36 | +model = model.to(device) |
| 37 | + |
| 38 | +# Processing images appropriately for the VGG16 model |
| 39 | +preprocess = transforms.Compose([ |
| 40 | + transforms.Resize((224, 224)), # Resize images to VGG16 input size |
| 41 | + transforms.ToTensor(), # Converting tensor format |
| 42 | + transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # Normalizing |
| 43 | +]) |
| 44 | + |
| 45 | +reference_tensor = preprocess(reference_image).unsqueeze(0).to(device) |
| 46 | +target_tensor = preprocess(target_image).unsqueeze(0).to(device) |
| 47 | + |
| 48 | +# Similarity Calculating Function |
| 49 | +def calculate_similarity(reference_tensor, target_tensor): |
| 50 | + # Feature maps of reference and target images |
| 51 | + reference_features = model.features(reference_tensor) |
| 52 | + target_features = model.features(target_tensor) |
| 53 | + |
| 54 | + # Similarity Calculating |
| 55 | + similarity = F.cosine_similarity(reference_features, target_features).mean() |
| 56 | + |
| 57 | + return similarity |
| 58 | + |
| 59 | +# Calculating of Similarity |
| 60 | +similarity_score = calculate_similarity(reference_tensor, target_tensor) |
| 61 | + |
| 62 | +# Similarity percenatage |
| 63 | +similarity_percentage = similarity_score.item() * 100 |
| 64 | + |
| 65 | +print(f"Benzerlik Skoru: {similarity_percentage:.2f}%") |
0 commit comments