forked from tnikolla/robot-grasp-detection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grasp_det.py
executable file
·162 lines (152 loc) · 6.63 KB
/
grasp_det.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
#!/usr/local/bin/python
'''
Training a network on cornell grasping dataset for detecting grasping positions.
'''
import sys
import argparse
import os.path
import glob
import tensorflow as tf
import numpy as np
from shapely.geometry import Polygon
import grasp_img_proc
from grasp_inf import inference
import time
TRAIN_FILE = '/root/dataset/cornell_grasping_dataset/train-cgd'
VALIDATE_FILE = '/root/dataset/cornell_grasping_dataset/validation-cgd'
def bboxes_to_grasps(bboxes):
# converting and scaling bounding boxes into grasps, g = {x, y, tan, h, w}
box = tf.unstack(bboxes, axis=1)
x = (box[0] + (box[4] - box[0])/2) * 0.35
y = (box[1] + (box[5] - box[1])/2) * 0.47
tan = (box[3] -box[1]) / (box[2] -box[0]) *0.47/0.35
h = tf.sqrt(tf.pow((box[2] -box[0])*0.35, 2) + tf.pow((box[3] -box[1])*0.47, 2))
w = tf.sqrt(tf.pow((box[6] -box[0])*0.35, 2) + tf.pow((box[7] -box[1])*0.47, 2))
return x, y, tan, h, w
def grasp_to_bbox(x, y, tan, h, w):
theta = tf.atan(tan)
edge1 = (x -w/2*tf.cos(theta) +h/2*tf.sin(theta), y -w/2*tf.sin(theta) -h/2*tf.cos(theta))
edge2 = (x +w/2*tf.cos(theta) +h/2*tf.sin(theta), y +w/2*tf.sin(theta) -h/2*tf.cos(theta))
edge3 = (x +w/2*tf.cos(theta) -h/2*tf.sin(theta), y +w/2*tf.sin(theta) +h/2*tf.cos(theta))
edge4 = (x -w/2*tf.cos(theta) -h/2*tf.sin(theta), y -w/2*tf.sin(theta) +h/2*tf.cos(theta))
return [edge1, edge2, edge3, edge4]
def run_training():
print(FLAGS.train_or_validation)
if FLAGS.train_or_validation == 'train':
print('distorted_inputs')
data_files_ = TRAIN_FILE
images, bboxes = grasp_img_proc.distorted_inputs(
[data_files_], FLAGS.num_epochs, batch_size=FLAGS.batch_size)
else:
print('inputs')
data_files_ = VALIDATE_FILE
images, bboxes = grasp_img_proc.inputs([data_files_])
x, y, tan, h, w = bboxes_to_grasps(bboxes)
x_hat, y_hat, tan_hat, h_hat, w_hat = tf.unstack(inference(images), axis=1) # list
# tangent of 85 degree is 11
tan_hat_confined = tf.minimum(11., tf.maximum(-11., tan_hat))
tan_confined = tf.minimum(11., tf.maximum(-11., tan))
# Loss function
gamma = tf.constant(10.)
loss = tf.reduce_sum(tf.pow(x_hat -x, 2) +tf.pow(y_hat -y, 2) + gamma*tf.pow(tan_hat_confined - tan_confined, 2) +tf.pow(h_hat -h, 2) +tf.pow(w_hat -w, 2))
train_op = tf.train.AdamOptimizer(epsilon=0.1).minimize(loss)
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess = tf.Session()
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
#save/restore model
d={}
l = ['w1', 'b1', 'w2', 'b2', 'w3', 'b3', 'w4', 'b4', 'w5', 'b5', 'w_fc1', 'b_fc1', 'w_fc2', 'b_fc2']
for i in l:
d[i] = [v for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) if v.name == i+':0'][0]
dg={}
lg = ['w1', 'b1', 'w2', 'b2', 'w3', 'b3', 'w4', 'b4', 'w5', 'b5', 'w_fc1', 'b_fc1', 'w_fc2', 'b_fc2', 'w_output', 'b_output']
for i in lg:
dg[i] = [v for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES) if v.name == i+':0'][0]
saver = tf.train.Saver(d)
saver_g = tf.train.Saver(dg)
#saver.restore(sess, "/root/grasp/grasp-detection/models/imagenet/m2/m2.ckpt")
saver_g.restore(sess, FLAGS.model_path)
try:
count = 0
step = 0
start_time = time.time()
while not coord.should_stop():
start_batch = time.time()
#train
if FLAGS.train_or_validation == 'train':
_, loss_value, x_value, x_model, tan_value, tan_model, h_value, h_model, w_value, w_model = sess.run([train_op, loss, x, x_hat, tan, tan_hat, h, h_hat, w, w_hat])
duration = time.time() - start_batch
if step % 100 == 0:
print('Step %d | loss = %s\n | x = %s\n | x_hat = %s\n | tan = %s\n | tan_hat = %s\n | h = %s\n | h_hat = %s\n | w = %s\n | w_hat = %s\n | (%.3f sec/batch\n')%(step, loss_value, x_value[:3], x_model[:3], tan_value[:3], tan_model[:3], h_value[:3], h_model[:3], w_value[:3], w_model[:3], duration)
if step % 1000 == 0:
saver_g.save(sess, FLAGS.model_path)
else:
bbox_hat = grasp_to_bbox(x_hat, y_hat, tan_hat, h_hat, w_hat)
bbox_value, bbox_model, tan_value, tan_model = sess.run([bboxes, bbox_hat, tan, tan_hat])
bbox_value = np.reshape(bbox_value, -1)
bbox_value = [(bbox_value[0]*0.35,bbox_value[1]*0.47),(bbox_value[2]*0.35,bbox_value[3]*0.47),(bbox_value[4]*0.35,bbox_value[5]*0.47),(bbox_value[6]*0.35,bbox_value[7]*0.47)]
p1 = Polygon(bbox_value)
p2 = Polygon(bbox_model)
iou = p1.intersection(p2).area / (p1.area +p2.area -p1.intersection(p2).area)
angle_diff = np.abs(np.arctan(tan_model)*180/np.pi -np.arctan(tan_value)*180/np.pi)
duration = time.time() -start_batch
if angle_diff < 30. and iou >= 0.25:
count+=1
print('image: %d | duration = %.2f | count = %d | iou = %.2f | angle_difference = %.2f' %(step, duration, count, iou, angle_diff))
step +=1
except tf.errors.OutOfRangeError:
print('Done training for %d epochs, %d steps, %.1f min.' % (FLAGS.num_epochs, step, (time.time()-start_time)/60))
finally:
coord.request_stop()
coord.join(threads)
sess.close()
def main(_):
run_training()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--learning_rate',
type=float,
default=0.001,
help='Initial learning rate.'
)
parser.add_argument(
'--data_dir',
type=str,
default='/root/imagenet-data',
help='Directory with training data.'
)
parser.add_argument(
'--num_epochs',
type=int,
default=None,
help='Number of epochs to run trainer.'
)
parser.add_argument(
'--batch_size',
type=int,
default=64,
help='Batch size.'
)
parser.add_argument(
'--log_dir',
type=str,
default='/tmp/tf',
help='Tensorboard log_dir.'
)
parser.add_argument(
'--model_path',
type=str,
default='/tmp/tf/model.ckpt',
help='Variables for the model.'
)
parser.add_argument(
'--train_or_validation',
type=str,
default='validation',
help='Train or evaluate the dataset'
)
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)