-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
203 lines (161 loc) · 6.81 KB
/
demo.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.autograd import Variable
import cv2
import sys
import numpy as np
from skimage import segmentation
import torch.nn.init
from pathlib import Path
use_cuda = torch.cuda.is_available()
parser = argparse.ArgumentParser(description='PyTorch Unsupervised Segmentation')
parser.add_argument('--nChannel', metavar='N', default=100, type=int,
help='number of channels')
parser.add_argument('--maxIter', metavar='T', default=1000, type=int,
help='number of maximum iterations')
parser.add_argument('--minLabels', metavar='minL', default=3, type=int,
help='minimum number of labels')
parser.add_argument('--lr', metavar='LR', default=0.1, type=float,
help='learning rate')
parser.add_argument('--nConv', metavar='M', default=2, type=int,
help='number of convolutional layers')
parser.add_argument('--num_superpixels', metavar='K', default=10000, type=int,
help='number of superpixels')
parser.add_argument('--compactness', metavar='C', default=100, type=float,
help='compactness of superpixels')
parser.add_argument('--visualize', metavar='1 or 0', default=0, type=int,
help='visualization flag')
parser.add_argument('--input', metavar='FILENAME',
help='input image file name', required=True)
args = parser.parse_args()
# CNN model
class MyNet(nn.Module):
def __init__(self,input_dim):
super(MyNet, self).__init__()
self.conv1 = nn.Conv2d(input_dim, args.nChannel, kernel_size=3, stride=1, padding=1 )
self.bn1 = nn.BatchNorm2d(args.nChannel)
self.conv2 = nn.ModuleList()
self.bn2 = nn.ModuleList()
for i in range(args.nConv-1):
self.conv2.append( nn.Conv2d(args.nChannel, args.nChannel, kernel_size=3, stride=1, padding=1 ) )
self.bn2.append( nn.BatchNorm2d(args.nChannel) )
self.conv3 = nn.Conv2d(args.nChannel, args.nChannel, kernel_size=1, stride=1, padding=0 )
self.bn3 = nn.BatchNorm2d(args.nChannel)
def forward(self, x):
x = self.conv1(x)
x = F.relu( x )
x = self.bn1(x)
for i in range(args.nConv-1):
x = self.conv2[i](x)
x = F.relu( x )
x = self.bn2[i](x)
x = self.conv3(x)
x = self.bn3(x)
return x
# load image
im = cv2.imread(args.input)
im_rgb = cv2.imread(args.input)
#norm_img = np.zeros(im.shape)
#im = cv2.GaussianBlur(im, (5,5), 1, 1)
data = torch.from_numpy( np.array([im.transpose( (2, 0, 1) ).astype('float32')/255.]) )
if use_cuda:
print("CUDA DATA")
data = data.cuda()
data = Variable(data)
# slic
import time
start = time.time()
im = cv2.cvtColor(im, cv2.COLOR_BGR2LAB )
#labels = SlicAvx2(num_components=10000, compactness=args.compactness, num_threads=4)
labels = segmentation.slic(im, compactness=args.compactness, n_segments=args.num_superpixels, min_size_factor=0.1)
print("TIME TAKEN SLIC: ", time.time() - start)
######################## Considering EDGE INFORMATION ######################
# Grey scale im
# Do Canny
# Get B&W Edge Map
# Get Labels for that
# Every Edge Component a Different Label
# bw = cv2.Canny(im, 10, 200)
# from skimage.measure import label
# bw_label = label(bw)
# labels[bw == 255] = bw_label[bw == 255] + np.max(labels)
##########################################################################
labels = labels.reshape(im.shape[0]*im.shape[1])
u_labels = np.unique(labels)
l_inds = []
for i in range(len(u_labels)):
l_inds.append( np.where( labels == u_labels[ i ] )[ 0 ] )
# train
model = MyNet( data.size(1) )
if use_cuda:
print("CUDA MODEL")
model.cuda()
model.train()
loss_fn = torch.nn.CrossEntropyLoss()
#optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=0.9)
optimizer = optim.Adam(model.parameters(), lr=args.lr)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience = 5, verbose = True)
label_colours = np.random.randint(255,size=(100,3))
for batch_idx in range(args.maxIter):
# forwarding
optimizer.zero_grad()
start_t = time.time()
output = model( data )[ 0 ]
output = output.permute( 1, 2, 0 ).contiguous().view( -1, args.nChannel )
ignore, target = torch.max( output, 1 )
im_target = target.data.cpu().numpy()
nLabels = len(np.unique(im_target))
if args.visualize:
im_target_rgb = np.array([label_colours[ c % 100 ] for c in im_target])
im_target_rgb = im_target_rgb.reshape( im.shape ).astype( np.uint8 )
#cv2_imshow( "output", im_target_rgb )
#cv2.waitKey(10)
cv2_imshow(im_target_rgb )
# superpixel refinement
# TODO: use Torch Variable instead of numpy for faster calculation
for i in range(len(l_inds)):
labels_per_sp = im_target[ l_inds[ i ] ]
u_labels_per_sp = np.unique( labels_per_sp )
hist = np.zeros( len(u_labels_per_sp) )
for j in range(len(hist)):
hist[ j ] = len( np.where( labels_per_sp == u_labels_per_sp[ j ] )[ 0 ] )
im_target[ l_inds[ i ] ] = u_labels_per_sp[ np.argmax( hist ) ]
target = torch.from_numpy( im_target )
if use_cuda:
target = target.cuda()
target = Variable( target )
loss = loss_fn(output, target)
loss.backward()
optimizer.step()
scheduler.step(loss)
#print (batch_idx, '/', args.maxIter, ':', nLabels, loss.data[0])
print (batch_idx, '/', args.maxIter, ':', nLabels, loss.item(), time.time() - start_t)
PATH = 'model.pth'
torch.save(model.state_dict(), PATH)
if nLabels <= args.minLabels:
print ("nLabels", nLabels, "reached minLabels", args.minLabels, ".")
break
from skimage.color import label2rgb
# save output image
if not args.visualize:
output = model( data )[ 0 ]
output = output.permute( 1, 2, 0 ).contiguous().view( -1, args.nChannel )
ignore, target = torch.max( output, 1 )
im_target = target.data.cpu().numpy()
im_target = im_target.reshape( im.shape[:-1] )
np.save('label.npy', im_target)
target_label = np.array([label_colours[ c % 100 ] for c in im_target])
im_target_rgb = label2rgb(im_target, image=im_rgb, kind = 'avg', bg_label = -1).astype( np.uint8 )
#im_target_label = label2rgb(im_target, bg_label = 0).astype( np.uint8 )
combined = np.hstack((im_target_rgb, target_label))
combined_orig_out = np.hstack((im_rgb, im_target_rgb))
target_label = target_label.reshape( im.shape ).astype( np.uint8 )
cv2.imwrite("PostProcessing.jpg", im_target)
cv2.imwrite( "output.png", im_target_rgb )
cv2.imwrite("Label.png", target_label)
cv2.imwrite("Combined.png", combined)
cv2.imwrite("ORIG-Compressed.png", combined_orig_out)