File size: 1,451 Bytes
4185a37
 
 
 
 
 
 
 
 
 
 
 
a7c4279
acd1620
a7c4279
6950e9c
a7c4279
 
 
4185a37
6950e9c
4185a37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
import random
import numpy as np
from PIL import Image
import torch

def set_seed(seed: int):
    """
    Set the seed for reproducibility across different libraries and devices.
    
    Args:
        seed (int): The seed value to set.
    """
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


def resize_and_center_crop(image, target_size=512):
    w, h = image.size
    scale = target_size / min(w, h)
    new_w = int(w * scale)
    new_h = int(h * scale)
    image_resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)

    left = (new_w - target_size) // 2
    top = (new_h - target_size) // 2
    right = left + target_size
    bottom = top + target_size
    image_cropped = image_resized.crop((left, top, right, bottom))

    return image_cropped


def resize_and_add_margin(image, target_size=512, background_color=(255, 255, 255)):
    w, h = image.size
    scale = target_size / max(w, h)
    new_w = int(w * scale)
    new_h = int(h * scale)
    image_resized = image.resize((new_w, new_h), Image.Resampling.LANCZOS)

    new_image = Image.new("RGB", (target_size, target_size), background_color)

    left = (target_size - new_w) // 2
    top = (target_size - new_h) // 2
    new_image.paste(image_resized, (left, top))

    return new_image