-
Notifications
You must be signed in to change notification settings - Fork 0
/
rgb2ycbcr.py
45 lines (43 loc) · 1.2 KB
/
rgb2ycbcr.py
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
import torch
def RGB2YCrCb(input_im):
im_flat = input_im.transpose(1, 3).transpose(
1, 2).reshape(-1, 3) # (nhw,c)
R = im_flat[:, 0]
G = im_flat[:, 1]
B = im_flat[:, 2]
Y = 0.299 * R + 0.587 * G + 0.114 * B
Cr = (R - Y) * 0.713 + 0.5
Cb = (B - Y) * 0.564 + 0.5
Y = torch.unsqueeze(Y, 1)
Cr = torch.unsqueeze(Cr, 1)
Cb = torch.unsqueeze(Cb, 1)
temp = torch.cat((Y, Cr, Cb), dim=1).cuda()
out = (
temp.reshape(
list(input_im.size())[0],
list(input_im.size())[2],
list(input_im.size())[3],
3,
)
.transpose(1, 3)
.transpose(2, 3)
)
return out
def YCrCb2RGB(input_im):
im_flat = input_im.transpose(1, 3).transpose(1, 2).reshape(-1, 3)
mat = torch.tensor(
[[1.0, 1.0, 1.0], [1.403, -0.714, 0.0], [0.0, -0.344, 1.773]]
).cuda()
bias = torch.tensor([0.0 / 255, -0.5, -0.5]).cuda()
temp = (im_flat + bias).mm(mat).cuda()
out = (
temp.reshape(
list(input_im.size())[0],
list(input_im.size())[2],
list(input_im.size())[3],
3,
)
.transpose(1, 3)
.transpose(2, 3)
)
return out