-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmisc.py
56 lines (42 loc) · 1.38 KB
/
misc.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
46
47
48
49
50
51
52
53
54
55
56
import os
from datetime import datetime
import time
import torchvision
import torch
from PIL import Image
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import pydensecrf.densecrf as dcrf
def check_mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def loadModel(model, path):
model.load_state_dict(torch.load(path))
def _sigmoid(x):
return 1 / (1 + np.exp(-x))
def crf_refine(img, annos):
assert img.dtype == np.uint8
assert annos.dtype == np.uint8
assert img.shape[:2] == annos.shape
# img and annos should be np array with data type uint8
EPSILON = 1e-8
M = 2 # salient or not
tau = 1.05
# Setup the CRF model
d = dcrf.DenseCRF2D(img.shape[1], img.shape[0], M)
anno_norm = annos / 255.
n_energy = -np.log((1.0 - anno_norm + EPSILON)) / (tau * _sigmoid(1 - anno_norm))
p_energy = -np.log(anno_norm + EPSILON) / (tau * _sigmoid(anno_norm))
U = np.zeros((M, img.shape[0] * img.shape[1]), dtype='float32')
U[0, :] = n_energy.flatten()
U[1, :] = p_energy.flatten()
d.setUnaryEnergy(U)
d.addPairwiseGaussian(sxy=3, compat=3)
d.addPairwiseBilateral(sxy=60, srgb=5, rgbim=img, compat=5)
# Do the inference
infer = np.array(d.inference(1)).astype('float32')
res = infer[1, :]
res = res * 255
res = res.reshape(img.shape[:2])
return res.astype('uint8')