前言:
本文記錄了使用Google發布的Object detection(July 1st, 2019)接口,完成了對標注目標的檢測。參考了很多博文,在此記錄配置過程,方便之后的再次調用。
首先貼出完整的代碼地址:https://github.com/tensorflow/models
Tensorflow Object Detection API:https://github.com/tensorflow/models/tree/master/research/object_detection
一、環境配置
參考網址:https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md
所有的環境都搭建在Anaconda創建的環境下
在windows10和Ubuntu下我都進行了配置,下方的配置會注明操作系統的區別
在上面參考網址上,已經明確給出了所需要的環境,直接用pip命令下載即可。
Protobuf 安裝
下載地址:https://github.com/google/protobuf/releases
win:
-
win10系統下載了
protoc-3.9.1-win64.zip,解壓后將其中的protoc.exe放置C:\Windows位置; -
通過命令窗口,定位到
models/research/目錄下,運行如下指令:# From /models/research/ protoc object_detection/protos/*.proto --python_out=.
此處我出現了
No such file or directory的錯誤采用一個個文件名單獨輸入的方式即可,例如:
# C:\Users\Zhucc\Desktop\ObjDec\models\research>protoc object_detection/protos/anchor_generator.proto --python_out=.
Linux:
-
通過pip安裝
pip install protobuf,我的版本為3.9.1 -
定位到
models/research/目錄下,運行如下指令:# From /models/research/ protoc object_detection/protos/*.proto --python_out=.
一行命令搞定,很舒服
Python環境配置:
win
-
轉到添加環境變量
-
可在系統變量/用戶變量選項框中新建環境變量
-
變量名:PYTHONPATH
-
變量值:
-
C:\Users\Zhucc\Desktop\ObjDec\models\research -
C:\Users\Zhucc\Desktop\ObjDec\models\research\slim
-
Linux
-
轉到
./models/research目錄下,運行如下命令:# From /models/research/ export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
COCO API 安裝
win:
COCO對於Windows是不支持的,因此需要通過其他的方式安裝
-
跳轉至:https://github.com/philferriere/cocoapi 將代碼下載好
-
win+r+cmd運行終端,進入*/cocoapi-master/PythonAPI -
運行如下命令:
python setup.py build_ext install運行完成后,會發現
_mask.c此文件被更新我電腦本身就存在Visual Studio2015,未出現任何錯誤
-
然后將
PythonAPI中的pycocotools放到*/models/research目錄下即可
參考網址:https://blog.csdn.net/benzhujie1245com/article/details/82686973
Linux:
只需按照官方的要求配置即可:
git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI make cp -r pycocotools <path_to_tensorflow>/models/research/
驗證安裝環境:
win:
-
進入
*/models/research/object_detection下 -
用
Jupiter Notebook打開object_detection_tutorial.ipynb
代碼解析:略,后續補充
-
運行即可,若出現被框出來的狗/人/風箏呀就說明你已經基本成功的在win10環境下配置了運行環境了
注意:其實官方的代碼是不會顯示圖片的,具體原因見如下網址:
https://blog.csdn.net/benzhujie1245com/article/details/82686973
但是!我改了后顯示圖片的FIgure會出現未響應的情況
因為只是驗證環境,將后兩句顯示的代碼改為:
img = Image.fromarray(image_np, 'RGB')
img.show()雖然有點傻,但是至少可以顯示出圖片來
Linux:
官方方法:
python object_detection/builders/model_builder_test.py # 結果: # ................ # ---------------------------------------------------------------------- # Ran 16 tests in 0.285s # OK
采用Jupiter Notebook
-
在服務器上下載
Jupiter Notebook:https://blog.csdn.net/wssywh/article/details/79214569
未試過,待補充
二、准備數據
在配置完成ObjectDetection后,在訓練模型前,需要對你要識別的物體數據進行處理。
首先說明文件夾目錄:
├─Data
│ ├─test
| | ├─images
│ │ ├─labels
│ │ ├─test.csv
| | └─test.tfrecord
│ └─train
| ├─images
│ ├─labels
│ ├─train.csv
| └─train.tfrecord
| ├─xml2csv.py
| ├─csv2tfrecords.py
數據准備
根據你需要識別的物體,對該物體進行數據的收集。
例如:此次我對人臉進行識別,隨意的找了80張圖片,作為我此次的訓練集(60)和驗證集(20)。
為了方便起見,圖采集的圖像進行重命名,以下為參考代碼:
# coding:utf-8
import os
import random
from PIL import Image
def deleteImages(file_path, file_list):
"""
刪除圖片
"""
for fileName in file_list:
command = "del " + file_path + "\\" + fileName
os.system(command)
def change_image_name(file_path, file_list):
"""
修改圖片名字
"""
for index, fileName in enumerate(file_list):
if fileName.find('.jpg') == -1:
continue
print(index, fileName)
newFileName = str('%03d' % index) + ".jpg"
print(newFileName)
im = Image.open(file_path + '/' + fileName)
im.save(file_path + '/' + newFileName)
def main():
# file_path = '.\\train\\images'
file_path = '.\\test\\images'
file_list = os.listdir(file_path)
random.shuffle(file_list)
change_image_name(file_path, file_list)
deleteImages(file_path, file_list)
if __name__ == '__main__':
main()
數據標注
在尋找完數據后,需要對數據進行標注,標注采用的工具如下:https://github.com/tzutalin/labelImg,根據你自身的環境,按照工具的說明進行操作即可。
我的環境為Anaconda+Windows,因此操作流程為:
# 1.Open the Anaconda Prompt and go to the labelImg directory # 2. conda install pyqt=5 # conda已經帶有了,略過 pyrcc5 -o libs/resources.py resources.qrc python labelImg.py python labelImg.py [IMAGE_PATH] [PRE-DEFINED CLASS FILE]
labelImage的安裝與使用參考鏈接:https://blog.csdn.net/jesse_mx/article/details/53606897
將標注后生成的xml文件放到相應的train\labels或test\labels文件夾下
不過此過程及其枯燥且耗時
數據轉換
數據轉換的步驟為:xml->csv->tfrecords
為什么不直接從xml轉換為tfrecords文件:-)
-
xml->csv代碼:
import glob
import pandas as pd
import xml.etree.ElementTree as ET
# 需要修改地方:選擇訓練集train還是測試集test
datasets = 'train'
csv_path = '.\\' + datasets + '\\'
xml_path = '.\\' + datasets + '\\labels\\'
def xml_to_csv(path):
"""將xml轉換成csv格式的數據"""
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():
xml_df = xml_to_csv(xml_path)
xml_df.to_csv(csv_path + datasets + '.csv', index=None)
print('Successfully converted %s\'s xml to csv.' % datasets)
if __name__ == '__main__':
main()
轉換完成后格式如下:
filename,width,height,class,xmin,ymin,xmax,ymax 000,500,333,mouth,265,256,370,315 000,500,333,eye,201,119,276,160 000,500,333,eye,363,114,447,158 000,500,333,face,151,7,498,326
-
csv->tfrecords代碼
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
# 此時是訓練集還是測試集
datasets = 'train'
flags = tf.app.flags
flags.DEFINE_string('csv_input', './%s/%s.csv' % (datasets, datasets), 'Path to the CSV input')
flags.DEFINE_string('output_path', './%s/%s.tfrecord' % (datasets, datasets), 'Path to output TFRecord')
flags.DEFINE_string('train_or_test', '%s' % datasets, 'train/test datasets')
FLAGS = flags.FLAGS
# 這里將label修改成自己的類別
def class_text_to_int(row_label):
if row_label == 'face':
return 1
if row_label == 'eye':
return 2
if row_label == 'mouth':
return 3
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, '%03d.jpg' % 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 = ('%03d.jpg' % 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']))
# 轉換為tfrecords需要的格式
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() + '\\' + FLAGS.train_or_test, 'images')
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()
print('Successfully created the TFRecords: {}'.format(FLAGS.output_path))
if __name__ == '__main__':
tf.app.run()
三、訓練模型
在完成上述兩部后,你可以開始真正的訓練你想要的模型了。
由於這種訓練太消耗電腦資源,因此將此過程放置服務器上進行
出於方便,我在object_detection目錄下新建了training文件夾,將所有自己添加的文件全部都放置改文件夾下,其目錄結構為:
├─data
├─model
│ └─ssd_mobilenet_v1_coco_2018_01_28
│ └─saved_model
│ └─variables
├─output_model
│ └─saved_model
│ └─variables
└─test_image
模型下載
在此處提供了各種各樣的可用於目標檢測的模型供你下載,先選個最簡單的ssd_mobilenet_v1_coco下載試試看效果;
解壓后的目錄結構如下:
|─ssd_mobilenet_v1_coco_2018_01_28
│ checkpoint
│ frozen_inference_graph.pb
│ model.ckpt.data-00000-of-00001
│ model.ckpt.index
│ model.ckpt.meta
│ pipeline.config
│
└─saved_model
│ saved_model.pb
│
└─variables
模型配置文件修改
-
在
data目錄下添加文件face_detection.pbtxt,其中的內容為:item { name: "face" id: 1 } item { name: "eye" id: 2 } item { name: "mouth" id: 3 }
這里面的id號和之前在csv中給定的id號需保持一致
-
將模型解壓文件夾中的
pipeline.config,復制到training目錄下 -
進行如下修改:
-
將文件中的所有
PATH_TO_BE_CONFIGURED修改成為自己的對應的文件夾路徑
# 我修改如下: fine_tune_checkpoint: "training/model/ssd_mobilenet_v1_coco_2018_01_28/model.ckpt" label_map_path: "training/data/face_detection.pbtxt" input_path: "training/data/train.tfrecord" label_map_path: "training/data/face_detection.pbtxt" input_path: "training/data/test.tfrecord"
出於引用配置文件的
model_main.py在object_detection目錄下,因此要加上training/ -
-
將
num_classes,改為你要識別的類別數,此處為3 -
將
eval_config下的num_examples修改成你測試集的圖片量,此處為20
至此,配置文件已經修改完成。
模型的訓練
之前所有的鋪墊都是為了此次模型的訓練,也終於要開始對模型進行訓練了。
-
通過命令
nvidia-smi查看可利用的空閑的GPU資源; -
通過命令
conda activate tensorflow1.12激活之前配置的環境; -
進入
models/research/object_detection文件夾中,為了方便起見,新建train_cmd.sh; -
用vim編輯
train_cmd.sh,輸入:# train #! /bin/bash CUDA_VISIBLE_DEVICES=1 \ # 指定gpu資源 python model_main.py \ # 需要運行的文件 --model_dir=training/model \ # 訓練中生成的模型保存的地方 --pipeline_config_path=training/pipeline.config \ # 配置文件地址 --num_train_steps=50000 # 訓練的步數
-
控制終端中輸入
bash train_cmd.sh,即開始進行訓練-
若出現無法找到object_detection模塊的問題,則回到
research目錄下,運行如下語句:
export PYTHONPATH=$PYTHONPATH:`pwd`:`pwd`/slim
-
查看訓練情況
改文件訓練時,並不會輸出loss與accuracy的情況,因此需要通過tensorboard進行查看。
在服務器使用tensorboard的方法:https://blog.csdn.net/sinat_35512245/article/details/82960937
進行上述配置后,進入object_detection文件中,輸入命令:
tensorboard --logdir=./training/model --port=6006
之后在本地的瀏覽器中輸入:localhost:12345即可查看遠程的tensorboard
tensorboard查看情況
-
IMAGES:在這里你可以查看你之前轉換的數據是否正確,例如此時我的數據如下:


-
GRAPHS:圖結構就定義在此處,有毅力有興趣者可以仔細看看數據時如何處理的,模型是如何架構的,方便后期的調參;
-
SCALARS:此處為訓練時的各種參數,例如loss值,learning_rate等參數,以下是經過50000次訓練后的結果圖:


模型的導出
在完成訓練后,我們需要將訓練生成的模型進行導出操作,將模型導出成為.pd的格式,操作流程如下:
-
在
object_detection目錄下新建create_pd.sh; -
將其中內容修改為:
# use export_inference_graph.py to create .pd file #! /bin/bash CUDA_VISIBLE_DEVICES=1 \ python export_inference_graph.py \ --input_type=image_tensor \ --pipeline_config_path=./training/pipeline.config \ --trained_checkpoint_prefix=training/model/model.ckpt-50000 \ --output_directory=./training/output_model
測試效果在win環境下進行,因此將生成的模型文件再導入到windows下
四、訓練結果測試
測試環境為本人的win10系統,在object_detection目錄下新建了model_test.py文件,代碼內容如下:
import os
import cv2
import sys
import numpy as np
from PIL import Image
import tensorflow as tf
# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")
from object_detection.utils import ops as utils_ops
from object_detection.utils import label_map_util
from object_detection.utils import visualization_utils as vis_util
# -----------------------------攝像頭類定義----------------------------- #
class Camera(object):
def __init__(self, channel):
self.capture = cv2.VideoCapture(channel)
self.fps = int(self.capture.get(cv2.CAP_PROP_FPS))
self.video_height = int(self.capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
self.video_width = int(self.capture.get(cv2.CAP_PROP_FRAME_WIDTH))
self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, self.video_width)
self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, self.video_height)
self.capture.set(cv2.CAP_PROP_FPS, self.fps)
def get_image(self):
"""
獲取圖像
"""
if self.capture.isOpened():
ret, frame = self.capture.read()
if ret is True:
print('get picture success')
return frame
else:
print('get picture failed')
return None
def release_camera(self):
"""
釋放攝像機資源
"""
self.capture.release()
cv2.destroyAllWindows()
# ------------------------------識別類定義----------------------------- #
class SSD_Model(object):
def __init__(self, PATH_TO_FROZEN_GRAPH, PATH_TO_LABELS):
self.PATH_TO_FROZEN_GRAPH = PATH_TO_FROZEN_GRAPH
# 添加需要識別的標簽
PATH_TO_LABELS = PATH_TO_LABELS
self.category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
self.detection_graph = self.load_model()
def load_model(self):
# 載入模型文件
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.PATH_TO_FROZEN_GRAPH, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
return detection_graph
def run_inference_for_single_image(self, image):
'''
對單幅圖像進行推斷
'''
graph = self.detection_graph
with graph.as_default():
with tf.Session() as sess:
# Get handles to input and output tensors
ops = tf.get_default_graph().get_operations()
all_tensor_names = {output.name for op in ops for output in op.outputs}
tensor_dict = {}
for key in [
'num_detections', 'detection_boxes', 'detection_scores',
'detection_classes', 'detection_masks']:
tensor_name = key + ':0'
if tensor_name in all_tensor_names:
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
tensor_name)
if 'detection_masks' in tensor_dict:
# The following processing is only for single image
detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
detection_masks, detection_boxes, image.shape[1], image.shape[2])
detection_masks_reframed = tf.cast(
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
# Follow the convention by adding back the batch dimension
tensor_dict['detection_masks'] = tf.expand_dims(
detection_masks_reframed, 0)
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
# Run inference
output_dict = sess.run(tensor_dict,
feed_dict={image_tensor: image})
# all outputs are float32 numpy arrays, so convert types as appropriate
output_dict['num_detections'] = int(output_dict['num_detections'][0])
output_dict['detection_classes'] = output_dict[
'detection_classes'][0].astype(np.int64)
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
output_dict['detection_scores'] = output_dict['detection_scores'][0]
if 'detection_masks' in output_dict:
output_dict['detection_masks'] = output_dict['detection_masks'][0]
return output_dict
def main():
# 開啟攝像頭
camera = Camera(0)
# 輸入模型
recognize = SSD_Model('./training/output_model/frozen_inference_graph.pb',
'./training/data/face_detection.pbtxt')
while camera.capture.isOpened():
# if True:
image = camera.get_image()
# image = cv2.imread('./training/test_image/007.jpg')
# the array based representation of the image will be used later in order to prepare the
# result image with boxes and labels on it.
image_np = np.array(image)
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
# Actual detection.
output_dict = recognize.run_inference_for_single_image(image_np_expanded)
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
output_dict['detection_boxes'],
output_dict['detection_classes'],
output_dict['detection_scores'],
recognize.category_index,
instance_masks=output_dict.get('detection_masks'),
use_normalized_coordinates=True,
line_thickness=2)
cv2.imshow('image', image_np)
cv2.waitKey(20)
if __name__ == "__main__":
main()
測試結果效果如下,上一張本人的帥照:-)


可見,訓練出來的結果是有效果的:-)
五、總結
-
首先感謝Google,封裝了那么健全的庫,能大大縮減開發的時間,提高開發的效率;
-
本次訓練采用了應該是最為基礎的模型,后續會嘗試更多的模型,比較不同模型之間的效果;
-
對於訓練的參數為做修改,例如學習率、優化方式等,后續會繼續努力理解代碼,進行修改來達到更好的效果;
參考:
https://blog.csdn.net/dy_guox/article/details/79111949
https://blog.csdn.net/Orienfish/article/details/81199911
https://blog.csdn.net/exploer_try/article/details/81434985
