Skip to content

Commit 58d5d64

Browse files
committed
Update yapf docs and run auto-formater for modified files.
1 parent 4521414 commit 58d5d64

File tree

8 files changed

+208
-170
lines changed

8 files changed

+208
-170
lines changed

efficientdet/dataset/create_coco_tfrecord.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,6 @@
4545
from dataset import label_map_util
4646
from dataset import tfrecord_util
4747

48-
4948
flags.DEFINE_boolean(
5049
'include_masks', False, 'Whether to include instance segmentations masks '
5150
'(PNG encoded) in the result. default: False.')
@@ -288,9 +287,8 @@ def _create_tf_record_from_coco_annotations(images_info_file,
288287

289288
logging.info('writing to output path: %s', output_path)
290289
writers = [
291-
tf.python_io.TFRecordWriter(
292-
output_path + '-%05d-of-%05d.tfrecord' % (i, num_shards))
293-
for i in range(num_shards)
290+
tf.python_io.TFRecordWriter(output_path + '-%05d-of-%05d.tfrecord' %
291+
(i, num_shards)) for i in range(num_shards)
294292
]
295293
images = _load_images_info(images_info_file)
296294

@@ -319,10 +317,11 @@ def _get_caption_annotation(image_id):
319317
pool = multiprocessing.Pool(FLAGS.num_threads)
320318
total_num_annotations_skipped = 0
321319
for idx, (_, tf_example, num_annotations_skipped) in enumerate(
322-
pool.imap(_pool_create_tf_example,
323-
[(image, image_dir, _get_object_annotation(image['id']),
324-
category_index, _get_caption_annotation(image['id']),
325-
include_masks) for image in images])):
320+
pool.imap(
321+
_pool_create_tf_example,
322+
[(image, image_dir, _get_object_annotation(image['id']),
323+
category_index, _get_caption_annotation(image['id']), include_masks)
324+
for image in images])):
326325
if idx % 100 == 0:
327326
logging.info('On image %d of %d', idx, len(images))
328327

efficientdet/dataset/create_pascal_tfrecord.py

Lines changed: 69 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@
3737

3838
from dataset import tfrecord_util
3939

40-
4140
flags.DEFINE_string('data_dir', '', 'Root directory to raw PASCAL VOC dataset.')
4241
flags.DEFINE_string('set', 'train', 'Convert training set, validation set or '
4342
'merged set.')
@@ -57,13 +56,29 @@
5756
YEARS = ['VOC2007', 'VOC2012', 'merged']
5857

5958
pascal_label_map_dict = {
60-
'background': 0, 'aeroplane': 1, 'bicycle': 2, 'bird': 3, 'boat': 4,
61-
'bottle': 5, 'bus': 6, 'car': 7, 'cat': 8, 'chair': 9, 'cow': 10,
62-
'diningtable': 11, 'dog': 12, 'horse': 13, 'motorbike': 14, 'person': 15,
63-
'pottedplant': 16, 'sheep': 17, 'sofa': 18, 'train': 19, 'tvmonitor': 20,
59+
'background': 0,
60+
'aeroplane': 1,
61+
'bicycle': 2,
62+
'bird': 3,
63+
'boat': 4,
64+
'bottle': 5,
65+
'bus': 6,
66+
'car': 7,
67+
'cat': 8,
68+
'chair': 9,
69+
'cow': 10,
70+
'diningtable': 11,
71+
'dog': 12,
72+
'horse': 13,
73+
'motorbike': 14,
74+
'person': 15,
75+
'pottedplant': 16,
76+
'sheep': 17,
77+
'sofa': 18,
78+
'train': 19,
79+
'tvmonitor': 20,
6480
}
6581

66-
6782
GLOBAL_IMG_ID = 0 # global image id.
6883
GLOBAL_ANN_ID = 0 # global annotation id.
6984

@@ -101,14 +116,14 @@ def dict_to_tf_example(data,
101116
by the raw data.
102117
103118
Args:
104-
data: dict holding PASCAL XML fields for a single image (obtained by
105-
running tfrecord_util.recursive_parse_xml_to_dict)
119+
data: dict holding PASCAL XML fields for a single image (obtained by running
120+
tfrecord_util.recursive_parse_xml_to_dict)
106121
dataset_directory: Path to root directory holding PASCAL dataset
107122
label_map_dict: A map from string label names to integers ids.
108123
ignore_difficult_instances: Whether to skip difficult instances in the
109124
dataset (default: False).
110-
image_subdirectory: String specifying subdirectory within the
111-
PASCAL dataset directory holding the actual image data.
125+
image_subdirectory: String specifying subdirectory within the PASCAL dataset
126+
directory holding the actual image data.
112127
ann_json_dict: annotation json dictionary.
113128
114129
Returns:
@@ -184,26 +199,42 @@ def dict_to_tf_example(data,
184199
}
185200
ann_json_dict['annotations'].append(ann)
186201

187-
example = tf.train.Example(features=tf.train.Features(feature={
188-
'image/height': tfrecord_util.int64_feature(height),
189-
'image/width': tfrecord_util.int64_feature(width),
190-
'image/filename': tfrecord_util.bytes_feature(
191-
data['filename'].encode('utf8')),
192-
'image/source_id': tfrecord_util.bytes_feature(
193-
str(image_id).encode('utf8')),
194-
'image/key/sha256': tfrecord_util.bytes_feature(key.encode('utf8')),
195-
'image/encoded': tfrecord_util.bytes_feature(encoded_jpg),
196-
'image/format': tfrecord_util.bytes_feature('jpeg'.encode('utf8')),
197-
'image/object/bbox/xmin': tfrecord_util.float_list_feature(xmin),
198-
'image/object/bbox/xmax': tfrecord_util.float_list_feature(xmax),
199-
'image/object/bbox/ymin': tfrecord_util.float_list_feature(ymin),
200-
'image/object/bbox/ymax': tfrecord_util.float_list_feature(ymax),
201-
'image/object/class/text': tfrecord_util.bytes_list_feature(classes_text),
202-
'image/object/class/label': tfrecord_util.int64_list_feature(classes),
203-
'image/object/difficult': tfrecord_util.int64_list_feature(difficult_obj),
204-
'image/object/truncated': tfrecord_util.int64_list_feature(truncated),
205-
'image/object/view': tfrecord_util.bytes_list_feature(poses),
206-
}))
202+
example = tf.train.Example(
203+
features=tf.train.Features(
204+
feature={
205+
'image/height':
206+
tfrecord_util.int64_feature(height),
207+
'image/width':
208+
tfrecord_util.int64_feature(width),
209+
'image/filename':
210+
tfrecord_util.bytes_feature(data['filename'].encode('utf8')),
211+
'image/source_id':
212+
tfrecord_util.bytes_feature(str(image_id).encode('utf8')),
213+
'image/key/sha256':
214+
tfrecord_util.bytes_feature(key.encode('utf8')),
215+
'image/encoded':
216+
tfrecord_util.bytes_feature(encoded_jpg),
217+
'image/format':
218+
tfrecord_util.bytes_feature('jpeg'.encode('utf8')),
219+
'image/object/bbox/xmin':
220+
tfrecord_util.float_list_feature(xmin),
221+
'image/object/bbox/xmax':
222+
tfrecord_util.float_list_feature(xmax),
223+
'image/object/bbox/ymin':
224+
tfrecord_util.float_list_feature(ymin),
225+
'image/object/bbox/ymax':
226+
tfrecord_util.float_list_feature(ymax),
227+
'image/object/class/text':
228+
tfrecord_util.bytes_list_feature(classes_text),
229+
'image/object/class/label':
230+
tfrecord_util.int64_list_feature(classes),
231+
'image/object/difficult':
232+
tfrecord_util.int64_list_feature(difficult_obj),
233+
'image/object/truncated':
234+
tfrecord_util.int64_list_feature(truncated),
235+
'image/object/view':
236+
tfrecord_util.bytes_list_feature(poses),
237+
}))
207238
return example
208239

209240

@@ -222,8 +253,8 @@ def main(_):
222253

223254
logging.info('writing to output path: %s', FLAGS.output_path)
224255
writers = [
225-
tf.python_io.TFRecordWriter(
226-
FLAGS.output_path + '-%05d-of-%05d.tfrecord' % (i, FLAGS.num_shards))
256+
tf.python_io.TFRecordWriter(FLAGS.output_path + '-%05d-of-%05d.tfrecord' %
257+
(i, FLAGS.num_shards))
227258
for i in range(FLAGS.num_shards)
228259
]
229260

@@ -260,9 +291,12 @@ def main(_):
260291
xml = etree.fromstring(xml_str)
261292
data = tfrecord_util.recursive_parse_xml_to_dict(xml)['annotation']
262293

263-
tf_example = dict_to_tf_example(data, FLAGS.data_dir, label_map_dict,
264-
FLAGS.ignore_difficult_instances,
265-
ann_json_dict=ann_json_dict)
294+
tf_example = dict_to_tf_example(
295+
data,
296+
FLAGS.data_dir,
297+
label_map_dict,
298+
FLAGS.ignore_difficult_instances,
299+
ann_json_dict=ann_json_dict)
266300
writers[idx % FLAGS.num_shards].write(tf_example.SerializeToString())
267301

268302
for writer in writers:

efficientdet/g3doc/faq.md

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,20 +7,30 @@ go/g3doc-canonical-go-links
77
freshness: { owner: 'tanmingxing' reviewed: '2020-05-09' }
88
*-->
99

10-
1110
[TOC]
1211

1312
## For Users
1413

1514
### How can I convert the saved model to tflite?
1615

17-
Unfortunately, there is no way to do that with the current public tensorflow release due to some issues in tf converter.
18-
We have some internal fixes, which could potentially be available with the next TensorFlow release.
16+
Unfortunately, there is no way to do that with the current public tensorflow
17+
release due to some issues in tf converter. We have some internal fixes, which
18+
could potentially be available with the next TensorFlow release.
1919

2020
## For Developers
2121

2222
### How can I format my code for PRs?
2323

24+
Please use [yapf](https://github.com/google/yapf) with option
25+
--style='{based_on_style: google, indent_width: 2}'. You can also save the
26+
following file to ~/.config/yapf/style:
27+
28+
[style]
29+
based_on_style = google
30+
indent_width = 2
31+
32+
If you want to check the format with lint, please run:
33+
2434
!pylint --rcfile=../.pylintrc your_file.py
2535

2636
### How can I run all tests?

efficientdet/inference.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -223,11 +223,9 @@ def det_post_process_combined(params, cls_outputs, box_outputs, scales,
223223
cls_outputs[level] = tf.transpose(cls_outputs[level], [0, 2, 3, 1])
224224
box_outputs[level] = tf.transpose(box_outputs[level], [0, 2, 3, 1])
225225

226-
cls_outputs_all.append(tf.reshape(
227-
cls_outputs[level],
228-
[batch_size, -1, params['num_classes']]))
229-
box_outputs_all.append(tf.reshape(
230-
box_outputs[level], [batch_size, -1, 4]))
226+
cls_outputs_all.append(
227+
tf.reshape(cls_outputs[level], [batch_size, -1, params['num_classes']]))
228+
box_outputs_all.append(tf.reshape(box_outputs[level], [batch_size, -1, 4]))
231229
cls_outputs_all = tf.concat(cls_outputs_all, 1)
232230
box_outputs_all = tf.concat(box_outputs_all, 1)
233231

@@ -261,11 +259,8 @@ def det_post_process_combined(params, cls_outputs, box_outputs, scales,
261259
ymax = tf.clip_by_value(nmsed_boxes[..., 2], 0, image_size[0]) * scales
262260
xmax = tf.clip_by_value(nmsed_boxes[..., 3], 0, image_size[1]) * scales
263261

264-
detection_list = [
265-
# Format: (image_ids, ymin, xmin, ymax, xmax, score, class)
266-
image_ids, ymin, xmin, ymax, xmax, nmsed_scores,
267-
tf.cast(nmsed_classes + 1, tf.float32)
268-
]
262+
classes = tf.cast(nmsed_classes + 1, tf.float32)
263+
detection_list = [image_ids, ymin, xmin, ymax, xmax, nmsed_scores, classes]
269264
detections = tf.stack(detection_list, axis=2, name='detections')
270265
return detections
271266

efficientdet/iou_utils.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,8 +169,8 @@ def iou_loss(pred_boxes: FloatType,
169169

170170
iou_loss_list = []
171171
for i in range(0, len(pred_boxes_list), 4):
172-
pred_boxes = pred_boxes_list[i: i + 4]
173-
target_boxes = target_boxes_list[i: i + 4]
172+
pred_boxes = pred_boxes_list[i:i + 4]
173+
target_boxes = target_boxes_list[i:i + 4]
174174

175175
# Compute mask.
176176
t_ymin, t_xmin, t_ymax, t_xmax = target_boxes
@@ -183,4 +183,3 @@ def iou_loss(pred_boxes: FloatType,
183183
if len(iou_loss_list) == 1:
184184
return iou_loss_list[0]
185185
return tf.reduce_sum(tf.stack(iou_loss_list), 0)
186-

efficientdet/model_inspect.py

Lines changed: 27 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
import utils
3737
from tensorflow.python.client import timeline # pylint: disable=g-direct-tensorflow-import
3838

39-
4039
flags.DEFINE_string('model_name', 'efficientdet-d0', 'Model.')
4140
flags.DEFINE_string('logdir', '/tmp/deff/', 'log directory.')
4241
flags.DEFINE_string('runmode', 'dry', 'Run mode: {freeze, bm, dry}')
@@ -117,7 +116,8 @@ def __init__(self,
117116

118117
self.model_config = model_config
119118

120-
def build_model(self, inputs: tf.Tensor,
119+
def build_model(self,
120+
inputs: tf.Tensor,
121121
is_training: bool = False) -> List[tf.Tensor]:
122122
"""Build model with inputs and labels and print out model stats."""
123123
logging.info('start building model')
@@ -166,7 +166,7 @@ def saved_model_inference(self, image_path_pattern, output_dir, **kwargs):
166166
num_batches = (len(all_files) + batch_size - 1) // batch_size
167167

168168
for i in range(num_batches):
169-
batch_files = all_files[i * batch_size: (i + 1) * batch_size]
169+
batch_files = all_files[i * batch_size:(i + 1) * batch_size]
170170
height, width = self.model_config.image_size
171171
images = [Image.open(f) for f in batch_files]
172172
if len(set([m.size for m in images])) > 1:
@@ -225,8 +225,9 @@ def saved_model_video(self, video_path: Text, output_video: Text, **kwargs):
225225
out_ptr = None
226226
if output_video:
227227
frame_width, frame_height = int(cap.get(3)), int(cap.get(4))
228-
out_ptr = cv2.VideoWriter(output_video, cv2.VideoWriter_fourcc(
229-
'm', 'p', '4', 'v'), 25, (frame_width, frame_height))
228+
out_ptr = cv2.VideoWriter(output_video,
229+
cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), 25,
230+
(frame_width, frame_height))
230231

231232
while cap.isOpened():
232233
# Capture frame-by-frame
@@ -320,7 +321,10 @@ def freeze_model(self) -> Tuple[Text, Text]:
320321

321322
return graphdef
322323

323-
def benchmark_model(self, warmup_runs, bm_runs, num_threads,
324+
def benchmark_model(self,
325+
warmup_runs,
326+
bm_runs,
327+
num_threads,
324328
trace_filename=None):
325329
"""Benchmark model."""
326330
if self.tensorrt:
@@ -385,16 +389,18 @@ def benchmark_model(self, warmup_runs, bm_runs, num_threads,
385389
run_options = tf.RunOptions()
386390
run_options.trace_level = tf.RunOptions.FULL_TRACE
387391
run_metadata = tf.RunMetadata()
388-
sess.run(output_name, feed_dict={input_name: img},
389-
options=run_options, run_metadata=run_metadata)
392+
sess.run(
393+
output_name,
394+
feed_dict={input_name: img},
395+
options=run_options,
396+
run_metadata=run_metadata)
390397
logging.info('Dumping trace to %s', trace_filename)
391398
trace_dir = os.path.dirname(trace_filename)
392399
if not tf.io.gfile.exists(trace_dir):
393400
tf.io.gfile.makedirs(trace_dir)
394401
with tf.io.gfile.GFile(trace_filename, 'w') as trace_file:
395402
trace = timeline.Timeline(step_stats=run_metadata.step_stats)
396-
trace_file.write(
397-
trace.generate_chrome_trace_format(show_memory=True))
403+
trace_file.write(trace.generate_chrome_trace_format(show_memory=True))
398404

399405
def convert_tr(self, graph_def, fetches):
400406
"""Convert to TensorRT."""
@@ -432,18 +438,20 @@ def run_model(self, runmode, **kwargs):
432438
if runmode == 'saved_model':
433439
self.export_saved_model(**config_dict)
434440
elif runmode == 'infer':
435-
self.inference_single_image(
436-
kwargs['input_image'], kwargs['output_image_dir'], **config_dict)
441+
self.inference_single_image(kwargs['input_image'],
442+
kwargs['output_image_dir'], **config_dict)
437443
elif runmode == 'saved_model_infer':
438-
self.saved_model_inference(
439-
kwargs['input_image'], kwargs['output_image_dir'], **config_dict)
444+
self.saved_model_inference(kwargs['input_image'],
445+
kwargs['output_image_dir'], **config_dict)
440446
elif runmode == 'saved_model_video':
441-
self.saved_model_video(
442-
kwargs['input_video'], kwargs['output_video'], **config_dict)
447+
self.saved_model_video(kwargs['input_video'], kwargs['output_video'],
448+
**config_dict)
443449
elif runmode == 'bm':
444-
self.benchmark_model(warmup_runs=5, bm_runs=kwargs.get('bm_runs', 10),
445-
num_threads=kwargs.get('threads', 0),
446-
trace_filename=kwargs.get('trace_filename', None))
450+
self.benchmark_model(
451+
warmup_runs=5,
452+
bm_runs=kwargs.get('bm_runs', 10),
453+
num_threads=kwargs.get('threads', 0),
454+
trace_filename=kwargs.get('trace_filename', None))
447455
else:
448456
raise ValueError('Unkown runmode {}'.format(runmode))
449457

efficientdet/model_inspect_test.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,8 +172,8 @@ def test_saved_model_graph_infer(self):
172172
tf.reset_default_graph()
173173

174174
# Use the frozen graph to do inference.
175-
inspector.saved_model_dir = os.path.join(
176-
self.params['saved_model_dir'], 'efficientdet-d0_frozen.pb')
175+
inspector.saved_model_dir = os.path.join(self.params['saved_model_dir'],
176+
'efficientdet-d0_frozen.pb')
177177
outdir = os.path.join(self.tempdir, 'pb_infer_imgout')
178178
os.mkdir(outdir)
179179

0 commit comments

Comments
 (0)