Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
iperov
GitHub Repository: iperov/deepfacelab
Path: blob/master/core/imagelib/common.py
628 views
1
import numpy as np
2
3
def random_crop(img, w, h):
4
height, width = img.shape[:2]
5
6
h_rnd = height - h
7
w_rnd = width - w
8
9
y = np.random.randint(0, h_rnd) if h_rnd > 0 else 0
10
x = np.random.randint(0, w_rnd) if w_rnd > 0 else 0
11
12
return img[y:y+height, x:x+width]
13
14
def normalize_channels(img, target_channels):
15
img_shape_len = len(img.shape)
16
if img_shape_len == 2:
17
h, w = img.shape
18
c = 0
19
elif img_shape_len == 3:
20
h, w, c = img.shape
21
else:
22
raise ValueError("normalize: incorrect image dimensions.")
23
24
if c == 0 and target_channels > 0:
25
img = img[...,np.newaxis]
26
c = 1
27
28
if c == 1 and target_channels > 1:
29
img = np.repeat (img, target_channels, -1)
30
c = target_channels
31
32
if c > target_channels:
33
img = img[...,0:target_channels]
34
c = target_channels
35
36
return img
37
38
def cut_odd_image(img):
39
h, w, c = img.shape
40
wm, hm = w % 2, h % 2
41
if wm + hm != 0:
42
img = img[0:h-hm,0:w-wm,:]
43
return img
44
45
def overlay_alpha_image(img_target, img_source, xy_offset=(0,0) ):
46
(h,w,c) = img_source.shape
47
if c != 4:
48
raise ValueError("overlay_alpha_image, img_source must have 4 channels")
49
50
x1, x2 = xy_offset[0], xy_offset[0] + w
51
y1, y2 = xy_offset[1], xy_offset[1] + h
52
53
alpha_s = img_source[:, :, 3] / 255.0
54
alpha_l = 1.0 - alpha_s
55
56
for c in range(0, 3):
57
img_target[y1:y2, x1:x2, c] = (alpha_s * img_source[:, :, c] +
58
alpha_l * img_target[y1:y2, x1:x2, c])
59