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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
import torch.nn.utils.spectral_norm as spectral_norm
|
| 6 |
+
from torch.autograd import Function
|
| 7 |
+
from utils import util, cielab
|
| 8 |
+
import cv2, math, random
|
| 9 |
+
|
| 10 |
+
def tensor2array(tensors):
|
| 11 |
+
arrays = tensors.detach().to("cpu").numpy()
|
| 12 |
+
return np.transpose(arrays, (0, 2, 3, 1))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def rgb2gray(color_batch):
|
| 16 |
+
#! gray = 0.299*R+0.587*G+0.114*B
|
| 17 |
+
gray_batch = color_batch[:, 0, ...] * 0.299 + color_batch[:, 1, ...] * 0.587 + color_batch[:, 2, ...] * 0.114
|
| 18 |
+
gray_batch = gray_batch.unsqueeze_(1)
|
| 19 |
+
return gray_batch
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def getParamsAmount(model):
|
| 23 |
+
params = list(model.parameters())
|
| 24 |
+
count = 0
|
| 25 |
+
for var in params:
|
| 26 |
+
l = 1
|
| 27 |
+
for j in var.size():
|
| 28 |
+
l *= j
|
| 29 |
+
count += l
|
| 30 |
+
return count
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def checkAverageGradient(model):
|
| 34 |
+
meanGrad, cnt = 0.0, 0
|
| 35 |
+
for name, parms in model.named_parameters():
|
| 36 |
+
if parms.requires_grad:
|
| 37 |
+
meanGrad += torch.mean(torch.abs(parms.grad))
|
| 38 |
+
cnt += 1
|
| 39 |
+
return meanGrad.item() / cnt
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_random_mask(N, H, W, minNum, maxNum):
|
| 43 |
+
binary_maps = np.zeros((N, H*W), np.float32)
|
| 44 |
+
for i in range(N):
|
| 45 |
+
locs = random.sample(range(0, H*W), random.randint(minNum,maxNum))
|
| 46 |
+
binary_maps[i, locs] = 1
|
| 47 |
+
return binary_maps.reshape(N,1,H,W)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def io_user_control(hint_mask, spix_colors, output=True):
|
| 51 |
+
cache_dir = '/apdcephfs/private_richardxia'
|
| 52 |
+
if output:
|
| 53 |
+
print('--- data saving')
|
| 54 |
+
mask_imgs = tensor2array(hint_mask) * 2.0 - 1.0
|
| 55 |
+
util.save_images_from_batch(mask_imgs, cache_dir, ['mask.png'], -1)
|
| 56 |
+
fake_gray = torch.zeros_like(spix_colors[:,[0],:,:])
|
| 57 |
+
spix_labs = torch.cat((fake_gray,spix_colors), dim=1)
|
| 58 |
+
spix_imgs = tensor2array(spix_labs)
|
| 59 |
+
util.save_normLabs_from_batch(spix_imgs, cache_dir, ['color.png'], -1)
|
| 60 |
+
return hint_mask, spix_colors
|
| 61 |
+
else:
|
| 62 |
+
print('--- data loading')
|
| 63 |
+
mask_img = cv2.imread(cache_dir+'/mask.png', cv2.IMREAD_GRAYSCALE)
|
| 64 |
+
mask_img = np.expand_dims(mask_img, axis=2) / 255.
|
| 65 |
+
hint_mask = torch.from_numpy(mask_img.transpose((2, 0, 1)))
|
| 66 |
+
hint_mask = hint_mask.unsqueeze(0).cuda()
|
| 67 |
+
bgr_img = cv2.imread(cache_dir+'/color.png', cv2.IMREAD_COLOR)
|
| 68 |
+
rgb_img = cv2.cvtColor(bgr_img, cv2.COLOR_BGR2RGB)
|
| 69 |
+
rgb_img = np.array(rgb_img / 255., np.float32)
|
| 70 |
+
lab_img = cv2.cvtColor(rgb_img, cv2.COLOR_RGB2LAB)
|
| 71 |
+
lab_img = torch.from_numpy(lab_img.transpose((2, 0, 1)))
|
| 72 |
+
ab_chans = lab_img[1:3,:,:] / 110.
|
| 73 |
+
spix_colors = ab_chans.unsqueeze(0).cuda()
|
| 74 |
+
return hint_mask.float(), spix_colors.float()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Quantize(Function):
|
| 78 |
+
@staticmethod
|
| 79 |
+
def forward(ctx, x):
|
| 80 |
+
ctx.save_for_backward(x)
|
| 81 |
+
y = x.round()
|
| 82 |
+
return y
|
| 83 |
+
|
| 84 |
+
@staticmethod
|
| 85 |
+
def backward(ctx, grad_output):
|
| 86 |
+
"""
|
| 87 |
+
In the backward pass we receive a Tensor containing the gradient of the loss
|
| 88 |
+
with respect to the output, and we need to compute the gradient of the loss
|
| 89 |
+
with respect to the input.
|
| 90 |
+
"""
|
| 91 |
+
inputX = ctx.saved_tensors
|
| 92 |
+
return grad_output
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def mark_color_hints(input_grays, target_ABs, gate_maps, kernel_size=3, base_ABs=None):
|
| 96 |
+
## to highlight the seeds with 1-pixel margin
|
| 97 |
+
binary_map = torch.where(gate_maps>0.7, torch.ones_like(gate_maps), torch.zeros_like(gate_maps))
|
| 98 |
+
center_mask = dilate_seeds(binary_map, kernel_size=kernel_size)
|
| 99 |
+
margin_mask = dilate_seeds(binary_map, kernel_size=kernel_size+2) - center_mask
|
| 100 |
+
## drop colors
|
| 101 |
+
dilated_seeds = dilate_seeds(gate_maps, kernel_size=kernel_size+2)
|
| 102 |
+
marked_grays = torch.where(margin_mask > 1e-5, torch.ones_like(gate_maps), input_grays)
|
| 103 |
+
if base_ABs is None:
|
| 104 |
+
marked_ABs = torch.where(center_mask < 1e-5, torch.zeros_like(target_ABs), target_ABs)
|
| 105 |
+
else:
|
| 106 |
+
marked_ABs = torch.where(margin_mask > 1e-5, torch.zeros_like(base_ABs), base_ABs)
|
| 107 |
+
marked_ABs = torch.where(center_mask > 1e-5, target_ABs, marked_ABs)
|
| 108 |
+
return torch.cat((marked_grays,marked_ABs), dim=1)
|
| 109 |
+
|
| 110 |
+
def dilate_seeds(gate_maps, kernel_size=3):
|
| 111 |
+
N,C,H,W = gate_maps.shape
|
| 112 |
+
input_unf = F.unfold(gate_maps, kernel_size, padding=kernel_size//2)
|
| 113 |
+
#! Notice: differentiable? just like max pooling?
|
| 114 |
+
dilated_seeds, _ = torch.max(input_unf, dim=1, keepdim=True)
|
| 115 |
+
output = F.fold(dilated_seeds, output_size=(H,W), kernel_size=1)
|
| 116 |
+
#print('-------', input_unf.shape)
|
| 117 |
+
return output
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
class RebalanceLoss(Function):
|
| 121 |
+
@staticmethod
|
| 122 |
+
def forward(ctx, data_input, weights):
|
| 123 |
+
ctx.save_for_backward(weights)
|
| 124 |
+
return data_input.clone()
|
| 125 |
+
|
| 126 |
+
@staticmethod
|
| 127 |
+
def backward(ctx, grad_output):
|
| 128 |
+
weights, = ctx.saved_tensors
|
| 129 |
+
# reweigh gradient pixelwise so that rare colors get a chance to
|
| 130 |
+
# contribute
|
| 131 |
+
grad_input = grad_output * weights
|
| 132 |
+
# second return value is None since we are not interested in the
|
| 133 |
+
# gradient with respect to the weights
|
| 134 |
+
return grad_input, None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class GetClassWeights:
|
| 138 |
+
def __init__(self, cielab, lambda_=0.5, device='cuda'):
|
| 139 |
+
prior = torch.from_numpy(cielab.gamut.prior).cuda()
|
| 140 |
+
uniform = torch.zeros_like(prior)
|
| 141 |
+
uniform[prior > 0] = 1 / (prior > 0).sum().type_as(uniform)
|
| 142 |
+
self.weights = 1 / ((1 - lambda_) * prior + lambda_ * uniform)
|
| 143 |
+
self.weights /= torch.sum(prior * self.weights)
|
| 144 |
+
|
| 145 |
+
def __call__(self, ab_actual):
|
| 146 |
+
return self.weights[ab_actual.argmax(dim=1, keepdim=True)]
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class ColorLabel:
|
| 150 |
+
def __init__(self, lambda_=0.5, device='cuda'):
|
| 151 |
+
self.cielab = cielab.CIELAB()
|
| 152 |
+
self.q_to_ab = torch.from_numpy(self.cielab.q_to_ab).to(device)
|
| 153 |
+
prior = torch.from_numpy(self.cielab.gamut.prior).to(device)
|
| 154 |
+
uniform = torch.zeros_like(prior)
|
| 155 |
+
uniform[prior>0] = 1 / (prior>0).sum().type_as(uniform)
|
| 156 |
+
self.weights = 1 / ((1-lambda_) * prior + lambda_ * uniform)
|
| 157 |
+
self.weights /= torch.sum(prior * self.weights)
|
| 158 |
+
|
| 159 |
+
def visualize_label(self, step=3):
|
| 160 |
+
height, width = 200, 313*step
|
| 161 |
+
label_lab = np.ones((height,width,3), np.float32)
|
| 162 |
+
for x in range(313):
|
| 163 |
+
ab = self.cielab.q_to_ab[x,:]
|
| 164 |
+
label_lab[:,step*x:step*(x+1),1:] = ab / 110.
|
| 165 |
+
label_lab[:,:,0] = np.zeros((height,width), np.float32)
|
| 166 |
+
return label_lab
|
| 167 |
+
|
| 168 |
+
@staticmethod
|
| 169 |
+
def _gauss_eval(x, mu, sigma):
|
| 170 |
+
norm = 1 / (2 * math.pi * sigma)
|
| 171 |
+
return norm * torch.exp(-torch.sum((x - mu)**2, dim=0) / (2 * sigma**2))
|
| 172 |
+
|
| 173 |
+
def get_classweights(self, batch_gt_indx):
|
| 174 |
+
#return self.weights[batch_gt_q.argmax(dim=1, keepdim=True)]
|
| 175 |
+
return self.weights[batch_gt_indx]
|
| 176 |
+
|
| 177 |
+
def encode_ab2ind(self, batch_ab, neighbours=5, sigma=5.0):
|
| 178 |
+
batch_ab = batch_ab * 110.
|
| 179 |
+
n, _, h, w = batch_ab.shape
|
| 180 |
+
m = n * h * w
|
| 181 |
+
# find nearest neighbours
|
| 182 |
+
ab_ = batch_ab.permute(1, 0, 2, 3).reshape(2, -1) # (2, n*h*w)
|
| 183 |
+
cdist = torch.cdist(self.q_to_ab, ab_.t())
|
| 184 |
+
nns = cdist.argsort(dim=0)[:neighbours, :]
|
| 185 |
+
# gaussian weighting
|
| 186 |
+
nn_gauss = batch_ab.new_zeros(neighbours, m)
|
| 187 |
+
for i in range(neighbours):
|
| 188 |
+
nn_gauss[i, :] = self._gauss_eval(self.q_to_ab[nns[i, :], :].t(), ab_, sigma)
|
| 189 |
+
nn_gauss /= nn_gauss.sum(dim=0, keepdim=True)
|
| 190 |
+
# expand
|
| 191 |
+
bins = self.cielab.gamut.EXPECTED_SIZE
|
| 192 |
+
q = batch_ab.new_zeros(bins, m)
|
| 193 |
+
q[nns, torch.arange(m).repeat(neighbours, 1)] = nn_gauss
|
| 194 |
+
return q.reshape(bins, n, h, w).permute(1, 0, 2, 3)
|
| 195 |
+
|
| 196 |
+
def decode_ind2ab(self, batch_q, T=0.38):
|
| 197 |
+
_, _, h, w = batch_q.shape
|
| 198 |
+
batch_q = F.softmax(batch_q, dim=1)
|
| 199 |
+
if T%1 == 0:
|
| 200 |
+
# take the T-st probable index
|
| 201 |
+
sorted_probs, batch_indexs = torch.sort(batch_q, dim=1, descending=True)
|
| 202 |
+
#print('checking [index]', batch_indexs[:,0:5,5,5])
|
| 203 |
+
#print('checking [probs]', sorted_probs[:,0:5,5,5])
|
| 204 |
+
batch_indexs = batch_indexs[:,T:T+1,:,:]
|
| 205 |
+
#batch_indexs = torch.where(sorted_probs[:,T:T+1,:,:] > 0.25, batch_indexs[:,T:T+1,:,:], batch_indexs[:,0:1,:,:])
|
| 206 |
+
ab = torch.stack([
|
| 207 |
+
self.q_to_ab.index_select(0, q_i.flatten()).reshape(h,w,2).permute(2,0,1)
|
| 208 |
+
for q_i in batch_indexs])
|
| 209 |
+
else:
|
| 210 |
+
batch_q = torch.exp(batch_q / T)
|
| 211 |
+
batch_q /= batch_q.sum(dim=1, keepdim=True)
|
| 212 |
+
a = torch.tensordot(batch_q, self.q_to_ab[:,0], dims=((1,), (0,)))
|
| 213 |
+
a = a.unsqueeze(dim=1)
|
| 214 |
+
b = torch.tensordot(batch_q, self.q_to_ab[:,1], dims=((1,), (0,)))
|
| 215 |
+
b = b.unsqueeze(dim=1)
|
| 216 |
+
ab = torch.cat((a, b), dim=1)
|
| 217 |
+
ab = ab / 110.
|
| 218 |
+
return ab.type(batch_q.dtype)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def init_spixel_grid(img_height, img_width, spixel_size=16):
|
| 222 |
+
# get spixel id for the final assignment
|
| 223 |
+
n_spixl_h = int(np.floor(img_height/spixel_size))
|
| 224 |
+
n_spixl_w = int(np.floor(img_width/spixel_size))
|
| 225 |
+
spixel_height = int(img_height / (1. * n_spixl_h))
|
| 226 |
+
spixel_width = int(img_width / (1. * n_spixl_w))
|
| 227 |
+
spix_values = np.int32(np.arange(0, n_spixl_w * n_spixl_h).reshape((n_spixl_h, n_spixl_w)))
|
| 228 |
+
|
| 229 |
+
def shift9pos(input, h_shift_unit=1, w_shift_unit=1):
|
| 230 |
+
# input should be padding as (c, 1+ height+1, 1+width+1)
|
| 231 |
+
input_pd = np.pad(input, ((h_shift_unit, h_shift_unit), (w_shift_unit, w_shift_unit)), mode='edge')
|
| 232 |
+
input_pd = np.expand_dims(input_pd, axis=0)
|
| 233 |
+
# assign to ...
|
| 234 |
+
top = input_pd[:, :-2 * h_shift_unit, w_shift_unit:-w_shift_unit]
|
| 235 |
+
bottom = input_pd[:, 2 * h_shift_unit:, w_shift_unit:-w_shift_unit]
|
| 236 |
+
left = input_pd[:, h_shift_unit:-h_shift_unit, :-2 * w_shift_unit]
|
| 237 |
+
right = input_pd[:, h_shift_unit:-h_shift_unit, 2 * w_shift_unit:]
|
| 238 |
+
center = input_pd[:,h_shift_unit:-h_shift_unit,w_shift_unit:-w_shift_unit]
|
| 239 |
+
bottom_right = input_pd[:, 2 * h_shift_unit:, 2 * w_shift_unit:]
|
| 240 |
+
bottom_left = input_pd[:, 2 * h_shift_unit:, :-2 * w_shift_unit]
|
| 241 |
+
top_right = input_pd[:, :-2 * h_shift_unit, 2 * w_shift_unit:]
|
| 242 |
+
top_left = input_pd[:, :-2 * h_shift_unit, :-2 * w_shift_unit]
|
| 243 |
+
shift_tensor = np.concatenate([ top_left, top, top_right,
|
| 244 |
+
left, center, right,
|
| 245 |
+
bottom_left, bottom, bottom_right], axis=0)
|
| 246 |
+
return shift_tensor
|
| 247 |
+
|
| 248 |
+
spix_idx_tensor_ = shift9pos(spix_values)
|
| 249 |
+
spix_idx_tensor = np.repeat(
|
| 250 |
+
np.repeat(spix_idx_tensor_, spixel_height, axis=1), spixel_width, axis=2)
|
| 251 |
+
spixel_id_tensor = torch.from_numpy(spix_idx_tensor).type(torch.float)
|
| 252 |
+
|
| 253 |
+
#! pixel coord feature maps
|
| 254 |
+
all_h_coords = np.arange(0, img_height, 1)
|
| 255 |
+
all_w_coords = np.arange(0, img_width, 1)
|
| 256 |
+
curr_pxl_coord = np.array(np.meshgrid(all_h_coords, all_w_coords, indexing='ij'))
|
| 257 |
+
coord_feat_tensor = np.concatenate([curr_pxl_coord[1:2, :, :], curr_pxl_coord[:1, :, :]])
|
| 258 |
+
coord_feat_tensor = torch.from_numpy(coord_feat_tensor).type(torch.float)
|
| 259 |
+
|
| 260 |
+
return spixel_id_tensor, coord_feat_tensor
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def split_spixels(assign_map, spixel_ids):
|
| 264 |
+
N,C,H,W = assign_map.shape
|
| 265 |
+
spixel_id_map = spixel_ids.expand(N,-1,-1,-1)
|
| 266 |
+
assig_max,_ = torch.max(assign_map, dim=1, keepdim=True)
|
| 267 |
+
assignment_ = torch.where(assign_map == assig_max, torch.ones(assign_map.shape).cuda(),torch.zeros(assign_map.shape).cuda())
|
| 268 |
+
## winner take all
|
| 269 |
+
new_spixl_map_ = spixel_id_map * assignment_
|
| 270 |
+
new_spixl_map = torch.sum(new_spixl_map_,dim=1,keepdim=True).type(torch.int)
|
| 271 |
+
return new_spixl_map
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def poolfeat(input, prob, sp_h=2, sp_w=2, need_entry_prob=False):
|
| 275 |
+
def feat_prob_sum(feat_sum, prob_sum, shift_feat):
|
| 276 |
+
feat_sum += shift_feat[:, :-1, :, :]
|
| 277 |
+
prob_sum += shift_feat[:, -1:, :, :]
|
| 278 |
+
return feat_sum, prob_sum
|
| 279 |
+
|
| 280 |
+
b, _, h, w = input.shape
|
| 281 |
+
h_shift_unit = 1
|
| 282 |
+
w_shift_unit = 1
|
| 283 |
+
p2d = (w_shift_unit, w_shift_unit, h_shift_unit, h_shift_unit)
|
| 284 |
+
feat_ = torch.cat([input, torch.ones([b, 1, h, w], device=input.device)], dim=1) # b* (n+1) *h*w
|
| 285 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 0, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 286 |
+
send_to_top_left = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, 2 * h_shift_unit:, 2 * w_shift_unit:]
|
| 287 |
+
feat_sum = send_to_top_left[:, :-1, :, :].clone()
|
| 288 |
+
prob_sum = send_to_top_left[:, -1:, :, :].clone()
|
| 289 |
+
|
| 290 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 1, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 291 |
+
top = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, 2 * h_shift_unit:, w_shift_unit:-w_shift_unit]
|
| 292 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, top)
|
| 293 |
+
|
| 294 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 2, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 295 |
+
top_right = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, 2 * h_shift_unit:, :-2 * w_shift_unit]
|
| 296 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, top_right)
|
| 297 |
+
|
| 298 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 3, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 299 |
+
left = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, h_shift_unit:-h_shift_unit, 2 * w_shift_unit:]
|
| 300 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, left)
|
| 301 |
+
|
| 302 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 4, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 303 |
+
center = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, h_shift_unit:-h_shift_unit, w_shift_unit:-w_shift_unit]
|
| 304 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, center)
|
| 305 |
+
|
| 306 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 5, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 307 |
+
right = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, h_shift_unit:-h_shift_unit, :-2 * w_shift_unit]
|
| 308 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, right)
|
| 309 |
+
|
| 310 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 6, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 311 |
+
bottom_left = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, :-2 * h_shift_unit, 2 * w_shift_unit:]
|
| 312 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, bottom_left)
|
| 313 |
+
|
| 314 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 7, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 315 |
+
bottom = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, :-2 * h_shift_unit, w_shift_unit:-w_shift_unit]
|
| 316 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, bottom)
|
| 317 |
+
|
| 318 |
+
prob_feat = F.avg_pool2d(feat_ * prob.narrow(1, 8, 1), kernel_size=(sp_h, sp_w), stride=(sp_h, sp_w)) # b * (n+1) * h* w
|
| 319 |
+
bottom_right = F.pad(prob_feat, p2d, mode='constant', value=0)[:, :, :-2 * h_shift_unit, :-2 * w_shift_unit]
|
| 320 |
+
feat_sum, prob_sum = feat_prob_sum(feat_sum, prob_sum, bottom_right)
|
| 321 |
+
pooled_feat = feat_sum / (prob_sum + 1e-8)
|
| 322 |
+
if need_entry_prob:
|
| 323 |
+
return pooled_feat, prob_sum
|
| 324 |
+
return pooled_feat
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def get_spixel_size(affinity_map, sp_h=2, sp_w=2, elem_thres=25):
|
| 328 |
+
N,C,H,W = affinity_map.shape
|
| 329 |
+
device = affinity_map.device
|
| 330 |
+
assign_max,_ = torch.max(affinity_map, dim=1, keepdim=True)
|
| 331 |
+
assign_map = torch.where(affinity_map==assign_max, torch.ones(affinity_map.shape, device=device), torch.zeros(affinity_map.shape, device=device))
|
| 332 |
+
## one_map = (N,1,H,W)
|
| 333 |
+
_, elem_num_maps = poolfeat(torch.ones(assign_max.shape, device=device), assign_map, sp_h, sp_w, True)
|
| 334 |
+
#all_one_map = torch.ones(elem_num_maps.shape).cuda()
|
| 335 |
+
#empty_mask = torch.where(elem_num_maps < elem_thres/256, all_one_map, 1-all_one_map)
|
| 336 |
+
return elem_num_maps
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def upfeat(input, prob, up_h=2, up_w=2):
|
| 340 |
+
# input b*n*H*W downsampled
|
| 341 |
+
# prob b*9*h*w
|
| 342 |
+
b, c, h, w = input.shape
|
| 343 |
+
|
| 344 |
+
h_shift = 1
|
| 345 |
+
w_shift = 1
|
| 346 |
+
|
| 347 |
+
p2d = (w_shift, w_shift, h_shift, h_shift)
|
| 348 |
+
feat_pd = F.pad(input, p2d, mode='constant', value=0)
|
| 349 |
+
|
| 350 |
+
gt_frm_top_left = F.interpolate(feat_pd[:, :, :-2 * h_shift, :-2 * w_shift], size=(h * up_h, w * up_w),mode='nearest')
|
| 351 |
+
feat_sum = gt_frm_top_left * prob.narrow(1,0,1)
|
| 352 |
+
|
| 353 |
+
top = F.interpolate(feat_pd[:, :, :-2 * h_shift, w_shift:-w_shift], size=(h * up_h, w * up_w), mode='nearest')
|
| 354 |
+
feat_sum += top * prob.narrow(1, 1, 1)
|
| 355 |
+
|
| 356 |
+
top_right = F.interpolate(feat_pd[:, :, :-2 * h_shift, 2 * w_shift:], size=(h * up_h, w * up_w), mode='nearest')
|
| 357 |
+
feat_sum += top_right * prob.narrow(1,2,1)
|
| 358 |
+
|
| 359 |
+
left = F.interpolate(feat_pd[:, :, h_shift:-w_shift, :-2 * w_shift], size=(h * up_h, w * up_w), mode='nearest')
|
| 360 |
+
feat_sum += left * prob.narrow(1, 3, 1)
|
| 361 |
+
|
| 362 |
+
center = F.interpolate(input, (h * up_h, w * up_w), mode='nearest')
|
| 363 |
+
feat_sum += center * prob.narrow(1, 4, 1)
|
| 364 |
+
|
| 365 |
+
right = F.interpolate(feat_pd[:, :, h_shift:-w_shift, 2 * w_shift:], size=(h * up_h, w * up_w), mode='nearest')
|
| 366 |
+
feat_sum += right * prob.narrow(1, 5, 1)
|
| 367 |
+
|
| 368 |
+
bottom_left = F.interpolate(feat_pd[:, :, 2 * h_shift:, :-2 * w_shift], size=(h * up_h, w * up_w), mode='nearest')
|
| 369 |
+
feat_sum += bottom_left * prob.narrow(1, 6, 1)
|
| 370 |
+
|
| 371 |
+
bottom = F.interpolate(feat_pd[:, :, 2 * h_shift:, w_shift:-w_shift], size=(h * up_h, w * up_w), mode='nearest')
|
| 372 |
+
feat_sum += bottom * prob.narrow(1, 7, 1)
|
| 373 |
+
|
| 374 |
+
bottom_right = F.interpolate(feat_pd[:, :, 2 * h_shift:, 2 * w_shift:], size=(h * up_h, w * up_w), mode='nearest')
|
| 375 |
+
feat_sum += bottom_right * prob.narrow(1, 8, 1)
|
| 376 |
+
|
| 377 |
+
return feat_sum
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def suck_and_spread(self, base_maps, seg_layers):
|
| 381 |
+
N,S,H,W = seg_layers.shape
|
| 382 |
+
base_maps = base_maps.unsqueeze(1)
|
| 383 |
+
seg_layers = seg_layers.unsqueeze(2)
|
| 384 |
+
## (N,S,C,1,1) = (N,1,C,H,W) * (N,S,1,H,W)
|
| 385 |
+
mean_val_layers = (base_maps * seg_layers).sum(dim=(3,4), keepdim=True) / (1e-5 + seg_layers.sum(dim=(3,4), keepdim=True))
|
| 386 |
+
## normalized to be sum one
|
| 387 |
+
weight_layers = seg_layers / (1e-5 + torch.sum(seg_layers, dim=1, keepdim=True))
|
| 388 |
+
## (N,S,C,H,W) = (N,S,C,1,1) * (N,S,1,H,W)
|
| 389 |
+
recon_maps = mean_val_layers * weight_layers
|
| 390 |
+
return recon_maps.sum(dim=1)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
#! copy from Richard Zhang [SIGGRAPH2017]
|
| 394 |
+
# RGB grid points maps to Lab range: L[0,100], a[-86.183,98,233], b[-107.857,94.478]
|
| 395 |
+
#------------------------------------------------------------------------------
|
| 396 |
+
def rgb2xyz(rgb): # rgb from [0,1]
|
| 397 |
+
# xyz_from_rgb = np.array([[0.412453, 0.357580, 0.180423],
|
| 398 |
+
# [0.212671, 0.715160, 0.072169],
|
| 399 |
+
# [0.019334, 0.119193, 0.950227]])
|
| 400 |
+
mask = (rgb > .04045).type(torch.FloatTensor)
|
| 401 |
+
if(rgb.is_cuda):
|
| 402 |
+
mask = mask.cuda()
|
| 403 |
+
rgb = (((rgb+.055)/1.055)**2.4)*mask + rgb/12.92*(1-mask)
|
| 404 |
+
x = .412453*rgb[:,0,:,:]+.357580*rgb[:,1,:,:]+.180423*rgb[:,2,:,:]
|
| 405 |
+
y = .212671*rgb[:,0,:,:]+.715160*rgb[:,1,:,:]+.072169*rgb[:,2,:,:]
|
| 406 |
+
z = .019334*rgb[:,0,:,:]+.119193*rgb[:,1,:,:]+.950227*rgb[:,2,:,:]
|
| 407 |
+
out = torch.cat((x[:,None,:,:],y[:,None,:,:],z[:,None,:,:]),dim=1)
|
| 408 |
+
return out
|
| 409 |
+
|
| 410 |
+
def xyz2rgb(xyz):
|
| 411 |
+
# array([[ 3.24048134, -1.53715152, -0.49853633],
|
| 412 |
+
# [-0.96925495, 1.87599 , 0.04155593],
|
| 413 |
+
# [ 0.05564664, -0.20404134, 1.05731107]])
|
| 414 |
+
r = 3.24048134*xyz[:,0,:,:]-1.53715152*xyz[:,1,:,:]-0.49853633*xyz[:,2,:,:]
|
| 415 |
+
g = -0.96925495*xyz[:,0,:,:]+1.87599*xyz[:,1,:,:]+.04155593*xyz[:,2,:,:]
|
| 416 |
+
b = .05564664*xyz[:,0,:,:]-.20404134*xyz[:,1,:,:]+1.05731107*xyz[:,2,:,:]
|
| 417 |
+
rgb = torch.cat((r[:,None,:,:],g[:,None,:,:],b[:,None,:,:]),dim=1)
|
| 418 |
+
#! sometimes reaches a small negative number, which causes NaNs
|
| 419 |
+
rgb = torch.max(rgb,torch.zeros_like(rgb))
|
| 420 |
+
mask = (rgb > .0031308).type(torch.FloatTensor)
|
| 421 |
+
if(rgb.is_cuda):
|
| 422 |
+
mask = mask.cuda()
|
| 423 |
+
rgb = (1.055*(rgb**(1./2.4)) - 0.055)*mask + 12.92*rgb*(1-mask)
|
| 424 |
+
return rgb
|
| 425 |
+
|
| 426 |
+
def xyz2lab(xyz):
|
| 427 |
+
# 0.95047, 1., 1.08883 # white
|
| 428 |
+
sc = torch.Tensor((0.95047, 1., 1.08883))[None,:,None,None]
|
| 429 |
+
if(xyz.is_cuda):
|
| 430 |
+
sc = sc.cuda()
|
| 431 |
+
xyz_scale = xyz/sc
|
| 432 |
+
mask = (xyz_scale > .008856).type(torch.FloatTensor)
|
| 433 |
+
if(xyz_scale.is_cuda):
|
| 434 |
+
mask = mask.cuda()
|
| 435 |
+
xyz_int = xyz_scale**(1/3.)*mask + (7.787*xyz_scale + 16./116.)*(1-mask)
|
| 436 |
+
L = 116.*xyz_int[:,1,:,:]-16.
|
| 437 |
+
a = 500.*(xyz_int[:,0,:,:]-xyz_int[:,1,:,:])
|
| 438 |
+
b = 200.*(xyz_int[:,1,:,:]-xyz_int[:,2,:,:])
|
| 439 |
+
out = torch.cat((L[:,None,:,:],a[:,None,:,:],b[:,None,:,:]),dim=1)
|
| 440 |
+
return out
|
| 441 |
+
|
| 442 |
+
def lab2xyz(lab):
|
| 443 |
+
y_int = (lab[:,0,:,:]+16.)/116.
|
| 444 |
+
x_int = (lab[:,1,:,:]/500.) + y_int
|
| 445 |
+
z_int = y_int - (lab[:,2,:,:]/200.)
|
| 446 |
+
if(z_int.is_cuda):
|
| 447 |
+
z_int = torch.max(torch.Tensor((0,)).cuda(), z_int)
|
| 448 |
+
else:
|
| 449 |
+
z_int = torch.max(torch.Tensor((0,)), z_int)
|
| 450 |
+
out = torch.cat((x_int[:,None,:,:],y_int[:,None,:,:],z_int[:,None,:,:]),dim=1)
|
| 451 |
+
mask = (out > .2068966).type(torch.FloatTensor)
|
| 452 |
+
if(out.is_cuda):
|
| 453 |
+
mask = mask.cuda()
|
| 454 |
+
out = (out**3.)*mask + (out - 16./116.)/7.787*(1-mask)
|
| 455 |
+
sc = torch.Tensor((0.95047, 1., 1.08883))[None,:,None,None]
|
| 456 |
+
sc = sc.to(out.device)
|
| 457 |
+
out = out*sc
|
| 458 |
+
return out
|
| 459 |
+
|
| 460 |
+
def rgb2lab(rgb, l_mean=50, l_norm=50, ab_norm=110):
|
| 461 |
+
#! input rgb: [0,1]
|
| 462 |
+
#! output lab: [-1,1]
|
| 463 |
+
lab = xyz2lab(rgb2xyz(rgb))
|
| 464 |
+
l_rs = (lab[:,[0],:,:]-l_mean) / l_norm
|
| 465 |
+
ab_rs = lab[:,1:,:,:] / ab_norm
|
| 466 |
+
out = torch.cat((l_rs,ab_rs),dim=1)
|
| 467 |
+
return out
|
| 468 |
+
|
| 469 |
+
def lab2rgb(lab_rs, l_mean=50, l_norm=50, ab_norm=110):
|
| 470 |
+
#! input lab: [-1,1]
|
| 471 |
+
#! output rgb: [0,1]
|
| 472 |
+
l_ = lab_rs[:,[0],:,:] * l_norm + l_mean
|
| 473 |
+
ab = lab_rs[:,1:,:,:] * ab_norm
|
| 474 |
+
lab = torch.cat((l_,ab), dim=1)
|
| 475 |
+
out = xyz2rgb(lab2xyz(lab))
|
| 476 |
+
return out
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
if __name__ == '__main__':
|
| 480 |
+
minL, minA, minB = 999., 999., 999.
|
| 481 |
+
maxL, maxA, maxB = 0., 0., 0.
|
| 482 |
+
for r in range(256):
|
| 483 |
+
print('h',r)
|
| 484 |
+
for g in range(256):
|
| 485 |
+
for b in range(256):
|
| 486 |
+
rgb = np.array([r,g,b], np.float32).reshape(1,1,-1) / 255.0
|
| 487 |
+
#lab_img = cv2.cvtColor(rgb, cv2.COLOR_RGB2LAB)
|
| 488 |
+
rgb = torch.from_numpy(rgb.transpose((2, 0, 1)))
|
| 489 |
+
rgb = rgb.reshape(1,3,1,1)
|
| 490 |
+
lab = rgb2lab(rgb)
|
| 491 |
+
lab[:,[0],:,:] = lab[:,[0],:,:] * 50 + 50
|
| 492 |
+
lab[:,1:,:,:] = lab[:,1:,:,:] * 110
|
| 493 |
+
lab = lab.squeeze()
|
| 494 |
+
lab_float = lab.numpy()
|
| 495 |
+
#print('zhang vs. cv2:', lab_float, lab_img.squeeze())
|
| 496 |
+
minL = min(lab_float[0], minL)
|
| 497 |
+
minA = min(lab_float[1], minA)
|
| 498 |
+
minB = min(lab_float[2], minB)
|
| 499 |
+
maxL = max(lab_float[0], maxL)
|
| 500 |
+
maxA = max(lab_float[1], maxA)
|
| 501 |
+
maxB = max(lab_float[2], maxB)
|
| 502 |
+
print('L:', minL, maxL)
|
| 503 |
+
print('A:', minA, maxA)
|
| 504 |
+
print('B:', minB, maxB)
|