Views
No views yet

1from torchvision import transforms
2import torch
3from PIL import Image
4from huggingface_hub import hf_hub_download
5import importlib.util
6import numpy as np
7import random
8
9device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10
11# Load the model class definition dynamically
12class_path = hf_hub_download(repo_id="PerceptCLIP/PerceptCLIP_IQA", filename="modeling.py")
13spec = importlib.util.spec_from_file_location("modeling", class_path)
14modeling = importlib.util.module_from_spec(spec)
15spec.loader.exec_module(modeling)
16
17# initialize a model
18ModelClass = modeling.clip_lora_model
19model = ModelClass().to(device)
20
21# Load pretrained model
22model_path = hf_hub_download(repo_id="PerceptCLIP/PerceptCLIP_IQA", filename="perceptCLIP_IQA.pth")
23model.load_state_dict(torch.load(model_path, map_location=device))
24model.eval()
25# Load an image
26image = Image.open("image_path.jpg").convert("RGB")
27
28# Preprocess and predict
29def IQA_preprocess():
30 random.seed(3407)
31 transform = transforms.Compose([
32 transforms.Resize((512,384)),
33 transforms.RandomCrop(size=(224,224)),
34 transforms.ToTensor(),
35 transforms.Normalize(mean=(0.48145466, 0.4578275, 0.40821073),
36 std=(0.26862954, 0.26130258, 0.27577711))
37 ])
38 return transform
39
40batch = torch.stack([IQA_preprocess()(image) for _ in range(15)]).to(device) # Shape: (15, 3, 224, 224)
41
42with torch.no_grad():
43 scores = model(batch).cpu().numpy()
44
45iqa_score = np.mean(scores)
46
47# maps the predicted score to [0,1] range
48min_pred = -6.52
49max_pred = 3.11
50
51normalized_score = ((iqa_score - min_pred) / (max_pred - min_pred))
52print(f"Predicted quality Score: {normalized_score:.4f}")1@article{zalcher2025don,
2 title={Don't Judge Before You CLIP: A Unified Approach for Perceptual Tasks},
3 author={Zalcher, Amit and Wasserman, Navve and Beliy, Roman and Heinimann, Oliver and Irani, Michal},
4 journal={arXiv preprint arXiv:2503.13260},
5 year={2025}
6}