1. ubuntu系統
https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md
offical install guide
https://pythonprogramming.net/testing-custom-object-detector-tensorflow-object-detection-api-tutorial/?completed=/training-custom-objects-tensorflow-object-detection-api-tutorial/,安裝+構建數據集+訓練+測試教程
error:
eric@eric-5g:~/models-master/research$ protoc object_detection/protos/model.proto --python_out=.
object_detection/protos/ssd.proto:87:3: Expected "required", "optional", or "repeated".
object_detection/protos/ssd.proto:87:12: Expected field name.
object_detection/protos/model.proto: Import "object_detection/protos/ssd.proto" was not found or had errors.
object_detection/protos/model.proto:12:5: "Ssd" is not defined.
because protoc version太低 ,update
1.下載protoc並解壓:
https://github.com/google/protobuf/releases/tag/v3.0.0
2.cd到的protoc的目錄下,並在終端執行:
sudo cp bin/protoc /usr/bin/protoc
3.確認是否安裝成功,在終端輸入:
protoc --version
error:
ImportError: No module named object_detection.builders
這是因爲下面這個命令寫錯了,踩過兩次坑了!pwd兩邊的不是',而是`。
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
整體來說,api的安裝還是比較簡單的,按照官網步驟進行即可。
構建數據集(轉數據集格式真的是real繁瑣了)
1.蒐集大量圖片
2.用labelImg工具對圖片進行標註
3.將xml文件轉換爲csv文件
import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET
def xml_to_csv(path):
xml_list = []
for xml_file in glob.glob(path + '/*.xml'):
tree = ET.parse(xml_file)
root = tree.getroot()
for member in root.findall('object'):
value = (root.find('filename').text,
int(root.find('size')[0].text),
int(root.find('size')[1].text),
member[0].text,
int(member[4][0].text),
int(member[4][1].text),
int(member[4][2].text),
int(member[4][3].text)
)
xml_list.append(value)
column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
xml_df = pd.DataFrame(xml_list, columns=column_name)
return xml_df
def main():
image_path = os.path.join(os.getcwd(), 'xml')#這裏os.getcwd()應該是得到終端進入的路徑吧,image_path=終端路徑/xml,xml爲存放xml文件的文件夾名稱
xml_df = xml_to_csv(image_path)
xml_df.to_csv('bs_labels.csv', index=None)
print('Successfully converted xml to csv.')
#這個main()函數是把終端路徑/xml裏面的xml文件轉換爲名爲bs_labels的csv文件,如果要將train,test的xml文件都轉成csv,則修改相應路徑,運行兩次即可。
最後得到的csv文件放在終端進入的路徑下。
main()
4.再將csv文件轉爲record文件(真是夠了!)
"""
Usage:
# From tensorflow/models/
# Create train data:
python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=train.record
# Create test data:
python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=test.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import io
import pandas as pd
import tensorflow as tf
from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict
flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')#待轉換的csv文件路徑
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')#轉後的record文件存放路徑
FLAGS = flags.FLAGS
# TO-DO replace this with label map
def class_text_to_int(row_label):
if row_label == 'BS':#改爲自己的label名
return 1
else:
None
def split(df, group):
data = namedtuple('data', ['filename', 'object'])
gb = df.groupby(group)
return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]
def create_tf_example(group, path):
with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = Image.open(encoded_jpg_io)
width, height = image.size
filename = group.filename.encode('utf8')
image_format = b'jpg'
xmins = []
xmaxs = []
ymins = []
ymaxs = []
classes_text = []
classes = []
for index, row in group.object.iterrows():
xmins.append(row['xmin'] / width)
xmaxs.append(row['xmax'] / width)
ymins.append(row['ymin'] / height)
ymaxs.append(row['ymax'] / height)
classes_text.append(row['class'].encode('utf8'))
classes.append(class_text_to_int(row['class']))
tf_example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/filename': dataset_util.bytes_feature(filename),
'image/source_id': dataset_util.bytes_feature(filename),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature(image_format),
'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
'image/object/class/label': dataset_util.int64_list_feature(classes),
}))
return tf_example
def main(_):
writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
path = os.path.join(os.getcwd(), 'BS')
examples = pd.read_csv(FLAGS.csv_input)
grouped = split(examples, 'filename')
for group in grouped:
tf_example = create_tf_example(group, path)
writer.write(tf_example.SerializeToString())
writer.close()
output_path = os.path.join(os.getcwd(), FLAGS.output_path)
print('Successfully created the TFRecords: {}'.format(output_path))
if __name__ == '__main__':
tf.app.run()
#終端輸入命令:
python generate_tfrecord.py --csv_input=xx.csv --output_path=xx.record
即可得到record文件。
在存放record同目錄下新建training文件夾,在training下新建object-detection.pbtxt文件
item {
id: 1
name: 'BS'#改爲自己要檢測的類別名
}
訓練過程
(參考芝士通心粉識別)
https://pythonprogramming.net/training-custom-objects-tensorflow-object-detection-api-tutorial/?completed=/creating-tfrecord-files-tensorflow-object-detection-api-tutorial/
1.將ipynb格式轉爲py格式(也可以直接在原文件上修改)
cd ~/models/research
jupyter note
左上角,點擊File-->Download as-->python,把ipynb格式保存爲py格式文件。
2.選擇
~/models/research/object_detection/samples/configs/ssd_mobilenet_v1_pets.config
~/models/research/object_detection/ssd_mobilenet_v1_coco_2017_11_17
將ssd_mobilenet_v1_pets.config放在training文件夾下。
修改ssd_mobilenet_v1_pets.config文件
# SSD with Mobilenet v1, configured for Oxford-IIIT Pets Dataset.
# Users should configure the fine_tune_checkpoint field in the train config as
# well as the label_map_path and input_path fields in the train_input_reader and
# eval_input_reader. Search for "PATH_TO_BE_CONFIGURED" to find the fields that
# should be configured.
model {
ssd {
num_classes: 1#改成自己的要檢測的類別數
box_coder {
faster_rcnn_box_coder {
y_scale: 10.0
x_scale: 10.0
height_scale: 5.0
width_scale: 5.0
}
}
matcher {
argmax_matcher {
matched_threshold: 0.5
unmatched_threshold: 0.5
ignore_thresholds: false
negatives_lower_than_unmatched: true
force_match_for_each_row: true
}
}
similarity_calculator {
iou_similarity {
}
}
anchor_generator {
ssd_anchor_generator {
num_layers: 6
min_scale: 0.2
max_scale: 0.95
aspect_ratios: 1.0
aspect_ratios: 2.0
aspect_ratios: 0.5
aspect_ratios: 3.0
aspect_ratios: 0.3333
}
}
image_resizer {
fixed_shape_resizer {
height: 300
width: 300
}
}
box_predictor {
convolutional_box_predictor {
min_depth: 0
max_depth: 0
num_layers_before_predictor: 0
use_dropout: false
dropout_keep_probability: 0.8
kernel_size: 1
box_code_size: 4
apply_sigmoid_to_scores: false
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
}
feature_extractor {
type: 'ssd_mobilenet_v1'
min_depth: 16
depth_multiplier: 1.0
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.00004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
train: true,
scale: true,
center: true,
decay: 0.9997,
epsilon: 0.001,
}
}
}
loss {
classification_loss {
weighted_sigmoid {
}
}
localization_loss {
weighted_smooth_l1 {
}
}
hard_example_miner {
num_hard_examples: 3000
iou_threshold: 0.99
loss_type: CLASSIFICATION
max_negatives_per_positive: 3
min_negatives_per_image: 0
}
classification_weight: 1.0
localization_weight: 1.0
}
normalize_loss_by_num_matches: true
post_processing {
batch_non_max_suppression {
score_threshold: 1e-8
iou_threshold: 0.6
max_detections_per_class: 100
max_total_detections: 100
}
score_converter: SIGMOID
}
}
}
train_config: {
batch_size: 24#這裏根據自己要求修改
optimizer {
rms_prop_optimizer: {
learning_rate: {
exponential_decay_learning_rate {
initial_learning_rate: 0.004
decay_steps: 800720
decay_factor: 0.95
}
}
momentum_optimizer_value: 0.9
decay: 0.9
epsilon: 1.0
}
}
fine_tune_checkpoint: "ssd_mobilenet_v1_coco_2017_11_17/model.ckpt"#這裏放剛纔下的checkpoint文件路徑
from_detection_checkpoint: true
load_all_detection_checkpoint_vars: true
# Note: The below line limits the training process to 200K steps, which we
# empirically found to be sufficient enough to train the pets dataset. This
# effectively bypasses the learning rate schedule (the learning rate will
# never decay). Remove the below line to train indefinitely.
num_steps: 200000
data_augmentation_options {
random_horizontal_flip {
}
}
data_augmentation_options {
ssd_random_crop {
}
}
}
train_input_reader: {
tf_record_input_reader {
input_path: "data/train.record"###############改成自己的路徑
}
label_map_path: "data/object-detection.pbtxt"##############改成自己的路徑
}
eval_config: {
metrics_set: "coco_detection_metrics"
num_examples: 1101
}###################
eval_input_reader: {
tf_record_input_reader {
input_path: "data/test.record"
}
label_map_path: "training/object-detection.pbtxt"
shuffle: false
num_readers: 1
}
3.訓練指令
先進入research目錄下,輸入命令行:
export PYTHONPATH=$PYTHONPATH:'pwd':'pwd'/slim
每當打開心終端,都要輸入上面的命令進行環境配置,否則運行api報錯。
之後進入object_detection目錄,輸入命令行:
python train.py --logtostderr --train_dir=training --pipeline_config_path=training/ssd_mobilenet_v1_pets.config
注意修改成自己training文件所在路徑
終端輸入tensorboard --logdir=training 可以實時監測訓練情況
4.測試指令
python export_inference_graph.py --input_type=image_tensor --pipeline_config_path=training/ssd_mobilenet_v1_pets.config --trained_checkpoint_prefix=training/model.ckpt-xx --output_directory=xx_inference_graph
之後,object_detection文件夾下應該出現xx_inference_graph文件。
終端輸入jupyter notebook
Variables模塊,修改,用以下代碼替換
# What model to download.
MODEL_NAME = 'xx_inference_graph'#之前生成的文件
# Path to frozen detection graph. This is the actual model that is used for the object detection.
PATH_TO_CKPT = MODEL_NAME + '/frozen_inference_graph.pb'
# List of the strings that is used to add correct label for each box.
PATH_TO_LABELS = os.path.join('training', 'object-detection.pbtxt')
NUM_CLASSES = 1#自己的類別
Detection模塊
TEST_IMAGE_PATHS = [ os.path.join(PATH_TO_TEST_IMAGES_DIR, 'image{}.jpg'.format(i)) for i in range(1, 3) ]
這句話的意思是檢測test_images文件夾下的image1,image2兩張圖片。
修改成自己要測試的圖片路徑,或者直接用自己的圖片將原文件夾中的圖片替換。
之後Cell-->Run All,就可以成功運行,測試自己的圖片。
殺掉某個gpu進程:
終端輸入nvidia-smi查看gpu使用情況,找到想要終止的Process name對應的PID號,終端輸入kill -9 PID
ubuntu16.04 打不開rar文件
解決辦法:
終端輸入
sudo apt-get install rar
sudo apt-get install p7zip-rar
sudo apt-get install p7zip-full
完美解決~
http://36kr.com/p/5090812.html,api的一個介紹
http://www.cnblogs.com/arkenstone/p/7237292.html,改成用opencv顯示圖片,更快一點。