Skip to content

Commit fb2ab67

Browse files
committed
Merge RealTimeObjectDetection1 into vendor/RealTimeObjetDetection1/
1 parent 98985e8 commit fb2ab67

14 files changed

Lines changed: 998 additions & 0 deletions

File tree

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
""" Sample TensorFlow XML-to-TFRecord converter
2+
3+
usage: generate_tfrecord.py [-h] [-x XML_DIR] [-l LABELS_PATH] [-o OUTPUT_PATH] [-i IMAGE_DIR] [-c CSV_PATH]
4+
5+
optional arguments:
6+
-h, --help show this help message and exit
7+
-x XML_DIR, --xml_dir XML_DIR
8+
Path to the folder where the input .xml files are stored.
9+
-l LABELS_PATH, --labels_path LABELS_PATH
10+
Path to the labels (.pbtxt) file.
11+
-o OUTPUT_PATH, --output_path OUTPUT_PATH
12+
Path of output TFRecord (.record) file.
13+
-i IMAGE_DIR, --image_dir IMAGE_DIR
14+
Path to the folder where the input image files are stored. Defaults to the same directory as XML_DIR.
15+
-c CSV_PATH, --csv_path CSV_PATH
16+
Path of output .csv file. If none provided, then no file will be written.
17+
"""
18+
19+
import os
20+
import glob
21+
import pandas as pd
22+
import io
23+
import xml.etree.ElementTree as ET
24+
import argparse
25+
26+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TensorFlow logging (1)
27+
import tensorflow.compat.v1 as tf
28+
from PIL import Image
29+
from object_detection.utils import dataset_util, label_map_util
30+
from collections import namedtuple
31+
32+
# Initiate argument parser
33+
parser = argparse.ArgumentParser(
34+
description="Sample TensorFlow XML-to-TFRecord converter")
35+
parser.add_argument("-x",
36+
"--xml_dir",
37+
help="Path to the folder where the input .xml files are stored.",
38+
type=str)
39+
parser.add_argument("-l",
40+
"--labels_path",
41+
help="Path to the labels (.pbtxt) file.", type=str)
42+
parser.add_argument("-o",
43+
"--output_path",
44+
help="Path of output TFRecord (.record) file.", type=str)
45+
parser.add_argument("-i",
46+
"--image_dir",
47+
help="Path to the folder where the input image files are stored. "
48+
"Defaults to the same directory as XML_DIR.",
49+
type=str, default=None)
50+
parser.add_argument("-c",
51+
"--csv_path",
52+
help="Path of output .csv file. If none provided, then no file will be "
53+
"written.",
54+
type=str, default=None)
55+
56+
args = parser.parse_args()
57+
58+
if args.image_dir is None:
59+
args.image_dir = args.xml_dir
60+
61+
label_map = label_map_util.load_labelmap(args.labels_path)
62+
label_map_dict = label_map_util.get_label_map_dict(label_map)
63+
64+
65+
def xml_to_csv(path):
66+
"""Iterates through all .xml files (generated by labelImg) in a given directory and combines
67+
them in a single Pandas dataframe.
68+
69+
Parameters:
70+
----------
71+
path : str
72+
The path containing the .xml files
73+
Returns
74+
-------
75+
Pandas DataFrame
76+
The produced dataframe
77+
"""
78+
79+
xml_list = []
80+
for xml_file in glob.glob(path + '/*.xml'):
81+
tree = ET.parse(xml_file)
82+
root = tree.getroot()
83+
for member in root.findall('object'):
84+
value = (root.find('filename').text,
85+
int(root.find('size')[0].text),
86+
int(root.find('size')[1].text),
87+
member[0].text,
88+
int(member[4][0].text),
89+
int(member[4][1].text),
90+
int(member[4][2].text),
91+
int(member[4][3].text)
92+
)
93+
xml_list.append(value)
94+
column_name = ['filename', 'width', 'height',
95+
'class', 'xmin', 'ymin', 'xmax', 'ymax']
96+
xml_df = pd.DataFrame(xml_list, columns=column_name)
97+
return xml_df
98+
99+
100+
def class_text_to_int(row_label):
101+
return label_map_dict[row_label]
102+
103+
104+
def split(df, group):
105+
data = namedtuple('data', ['filename', 'object'])
106+
gb = df.groupby(group)
107+
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
108+
109+
110+
def create_tf_example(group, path):
111+
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
112+
encoded_jpg = fid.read()
113+
encoded_jpg_io = io.BytesIO(encoded_jpg)
114+
image = Image.open(encoded_jpg_io)
115+
width, height = image.size
116+
117+
filename = group.filename.encode('utf8')
118+
image_format = b'jpg'
119+
xmins = []
120+
xmaxs = []
121+
ymins = []
122+
ymaxs = []
123+
classes_text = []
124+
classes = []
125+
126+
for index, row in group.object.iterrows():
127+
xmins.append(row['xmin'] / width)
128+
xmaxs.append(row['xmax'] / width)
129+
ymins.append(row['ymin'] / height)
130+
ymaxs.append(row['ymax'] / height)
131+
classes_text.append(row['class'].encode('utf8'))
132+
classes.append(class_text_to_int(row['class']))
133+
134+
tf_example = tf.train.Example(features=tf.train.Features(feature={
135+
'image/height': dataset_util.int64_feature(height),
136+
'image/width': dataset_util.int64_feature(width),
137+
'image/filename': dataset_util.bytes_feature(filename),
138+
'image/source_id': dataset_util.bytes_feature(filename),
139+
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
140+
'image/format': dataset_util.bytes_feature(image_format),
141+
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
142+
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
143+
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
144+
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
145+
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
146+
'image/object/class/label': dataset_util.int64_list_feature(classes),
147+
}))
148+
return tf_example
149+
150+
151+
def main(_):
152+
153+
writer = tf.python_io.TFRecordWriter(args.output_path)
154+
path = os.path.join(args.image_dir)
155+
examples = xml_to_csv(args.xml_dir)
156+
grouped = split(examples, 'filename')
157+
for group in grouped:
158+
tf_example = create_tf_example(group, path)
159+
writer.write(tf_example.SerializeToString())
160+
writer.close()
161+
print('Successfully created the TFRecord file: {}'.format(args.output_path))
162+
if args.csv_path is not None:
163+
examples.to_csv(args.csv_path, index=None)
164+
print('Successfully created the CSV file: {}'.format(args.csv_path))
165+
166+
167+
if __name__ == '__main__':
168+
tf.app.run()

vendor/RealTimeObjectDetection1/Tensorflow/workspace/annotations/.gitkeep

Whitespace-only changes.

vendor/RealTimeObjectDetection1/Tensorflow/workspace/images/test/.gitkeep

Whitespace-only changes.

vendor/RealTimeObjectDetection1/Tensorflow/workspace/images/train/.gitkeep

Whitespace-only changes.

vendor/RealTimeObjectDetection1/Tensorflow/workspace/models/.gitkeep

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
model_checkpoint_path: "ckpt-0"
2+
all_model_checkpoint_paths: "ckpt-0"
3+
all_model_checkpoint_timestamps: 1594332511.5251744
4+
last_preserved_timestamp: 1594332507.0004687
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
model {
2+
ssd {
3+
num_classes: 90
4+
image_resizer {
5+
fixed_shape_resizer {
6+
height: 320
7+
width: 320
8+
}
9+
}
10+
feature_extractor {
11+
type: "ssd_mobilenet_v2_fpn_keras"
12+
depth_multiplier: 1.0
13+
min_depth: 16
14+
conv_hyperparams {
15+
regularizer {
16+
l2_regularizer {
17+
weight: 3.9999998989515007e-05
18+
}
19+
}
20+
initializer {
21+
random_normal_initializer {
22+
mean: 0.0
23+
stddev: 0.009999999776482582
24+
}
25+
}
26+
activation: RELU_6
27+
batch_norm {
28+
decay: 0.996999979019165
29+
scale: true
30+
epsilon: 0.0010000000474974513
31+
}
32+
}
33+
use_depthwise: true
34+
override_base_feature_extractor_hyperparams: true
35+
fpn {
36+
min_level: 3
37+
max_level: 7
38+
additional_layer_depth: 128
39+
}
40+
}
41+
box_coder {
42+
faster_rcnn_box_coder {
43+
y_scale: 10.0
44+
x_scale: 10.0
45+
height_scale: 5.0
46+
width_scale: 5.0
47+
}
48+
}
49+
matcher {
50+
argmax_matcher {
51+
matched_threshold: 0.5
52+
unmatched_threshold: 0.5
53+
ignore_thresholds: false
54+
negatives_lower_than_unmatched: true
55+
force_match_for_each_row: true
56+
use_matmul_gather: true
57+
}
58+
}
59+
similarity_calculator {
60+
iou_similarity {
61+
}
62+
}
63+
box_predictor {
64+
weight_shared_convolutional_box_predictor {
65+
conv_hyperparams {
66+
regularizer {
67+
l2_regularizer {
68+
weight: 3.9999998989515007e-05
69+
}
70+
}
71+
initializer {
72+
random_normal_initializer {
73+
mean: 0.0
74+
stddev: 0.009999999776482582
75+
}
76+
}
77+
activation: RELU_6
78+
batch_norm {
79+
decay: 0.996999979019165
80+
scale: true
81+
epsilon: 0.0010000000474974513
82+
}
83+
}
84+
depth: 128
85+
num_layers_before_predictor: 4
86+
kernel_size: 3
87+
class_prediction_bias_init: -4.599999904632568
88+
share_prediction_tower: true
89+
use_depthwise: true
90+
}
91+
}
92+
anchor_generator {
93+
multiscale_anchor_generator {
94+
min_level: 3
95+
max_level: 7
96+
anchor_scale: 4.0
97+
aspect_ratios: 1.0
98+
aspect_ratios: 2.0
99+
aspect_ratios: 0.5
100+
scales_per_octave: 2
101+
}
102+
}
103+
post_processing {
104+
batch_non_max_suppression {
105+
score_threshold: 9.99999993922529e-09
106+
iou_threshold: 0.6000000238418579
107+
max_detections_per_class: 100
108+
max_total_detections: 100
109+
use_static_shapes: false
110+
}
111+
score_converter: SIGMOID
112+
}
113+
normalize_loss_by_num_matches: true
114+
loss {
115+
localization_loss {
116+
weighted_smooth_l1 {
117+
}
118+
}
119+
classification_loss {
120+
weighted_sigmoid_focal {
121+
gamma: 2.0
122+
alpha: 0.25
123+
}
124+
}
125+
classification_weight: 1.0
126+
localization_weight: 1.0
127+
}
128+
encode_background_as_zeros: true
129+
normalize_loc_loss_by_codesize: true
130+
inplace_batchnorm_update: true
131+
freeze_batchnorm: false
132+
}
133+
}
134+
train_config {
135+
batch_size: 128
136+
data_augmentation_options {
137+
random_horizontal_flip {
138+
}
139+
}
140+
data_augmentation_options {
141+
random_crop_image {
142+
min_object_covered: 0.0
143+
min_aspect_ratio: 0.75
144+
max_aspect_ratio: 3.0
145+
min_area: 0.75
146+
max_area: 1.0
147+
overlap_thresh: 0.0
148+
}
149+
}
150+
sync_replicas: true
151+
optimizer {
152+
momentum_optimizer {
153+
learning_rate {
154+
cosine_decay_learning_rate {
155+
learning_rate_base: 0.07999999821186066
156+
total_steps: 50000
157+
warmup_learning_rate: 0.026666000485420227
158+
warmup_steps: 1000
159+
}
160+
}
161+
momentum_optimizer_value: 0.8999999761581421
162+
}
163+
use_moving_average: false
164+
}
165+
fine_tune_checkpoint: "PATH_TO_BE_CONFIGURED"
166+
num_steps: 50000
167+
startup_delay_steps: 0.0
168+
replicas_to_aggregate: 8
169+
max_number_of_boxes: 100
170+
unpad_groundtruth_tensors: false
171+
fine_tune_checkpoint_type: "classification"
172+
fine_tune_checkpoint_version: V2
173+
}
174+
train_input_reader {
175+
label_map_path: "PATH_TO_BE_CONFIGURED"
176+
tf_record_input_reader {
177+
input_path: "PATH_TO_BE_CONFIGURED"
178+
}
179+
}
180+
eval_config {
181+
metrics_set: "coco_detection_metrics"
182+
use_moving_averages: false
183+
}
184+
eval_input_reader {
185+
label_map_path: "PATH_TO_BE_CONFIGURED"
186+
shuffle: false
187+
num_epochs: 1
188+
tf_record_input_reader {
189+
input_path: "PATH_TO_BE_CONFIGURED"
190+
}
191+
}

0 commit comments

Comments
 (0)