File size: 1,419 Bytes
67d69a3
 
 
 
a1732e3
67d69a3
a3814f8
 
67d69a3
 
89e4ae0
 
 
 
 
 
 
 
 
 
 
67d69a3
 
 
89e4ae0
f1ac6b9
67d69a3
814e69a
89e4ae0
 
 
 
67d69a3
 
a0f5d9f
67d69a3
a1732e3
 
 
 
 
 
 
 
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
from PIL import Image

import torch
import torchvision.transforms as transforms
from safetensors.torch import load_file

def preprocess_img(img, img_size, normalize=False):
    if type(img) == str: img = Image.open(img)
    original_size = img.size
    
    if normalize:
        transform = transforms.Compose([
            transforms.Resize((img_size, img_size)),
            transforms.ToTensor(),
            transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
        ])
    else:
        transform = transforms.Compose([
            transforms.Resize((img_size, img_size)),
            transforms.ToTensor()
        ])
    img = transform(img).unsqueeze(0)
    return img, original_size

def postprocess_img(img, original_size, normalize=False):
    img = img.detach().cpu().squeeze(0)
    
    # Denormalize the image
    if normalize:
        mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
        std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
        img = img * std + mean
    img = torch.clamp(img, 0, 1)
    
    img = transforms.ToPILImage()(img)
    img = img.resize(original_size, Image.Resampling.LANCZOS)
    return img

def load_model_without_module(model, model_path, device):
    state_dict = {
        k[7:] if k.startswith('module.') else k: v 
        for k, v in load_file(model_path, device=device).items()
    }
    model.load_state_dict(state_dict)