欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

基于MobileNetV2-SSD缺陷检测

程序员文章站 2022-06-09 18:07:20
基于MobileNetV2-SSD缺陷检测(1) SSD论文连接(2) MobileNetV2连接实验部分一 环境搭配win10pycharmanacondacuda + cudnnpython 3.xtensorflow-gpu下载代码库下载protoc作用是将Tensorflow object detection API模型文件中的.pro文件编译成python文件。直接输入:protoc ./object_detection/protos/*.proto --python_o...

基于MobileNetV2-SSD缺陷检测

(1) SSD论文连接
(2) MobileNetV2连接

实验部分

一 环境搭配

win10
pycharm
anaconda
cuda + cudnn
python 3.x
tensorflow-gpu
下载代码库
下载protoc作用是将Tensorflow object detection API模型文件中的.pro
文件编译成python文件。直接输入:protoc ./object_detection/protos/*.proto --python_out=. 就可以快速编译所有文件

添加两个环境变量:
\models\research
\models\research\slim
基于MobileNetV2-SSD缺陷检测安装research & slim
cd slim
python setup.py install

测试是否安装成功(research目录)
python object_detection/builders/model_builder_test.py
安装成功会显示ok

二制作数据集

下载labelimg-master
打开cmd, 进入labelImg目录:
运行
pyrcc5 -o resources.py resources.qrc命令
python labelImg.py
就可以打开labelImg了
通过画矩形框,打上标签,生成xml文件新建data文件夹,并生成train,test两个子文件夹
基于MobileNetV2-SSD缺陷检测
xlm转csv

"""
Created on 2020 7 11

@author: Huang hanlin
"""

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET

os.chdir('E:\\model-master\\research\\object_detection\\data\\imagess\\test')
path = 'E:\\model-master\\research\\object_detection\\data\\imagess\\test'

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 = path
    xml_df = xml_to_csv(image_path)
    xml_df.to_csv('maosi_test.csv', index=None)
    print('Successfully converted xml to csv.')


main()

csv生成tf文件

from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
#python generate_tfrecord.py --csv_input=maosi_train.csv  --image_dir=train --output_path=train.record
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')
flags.DEFINE_string('image_dir', '', 'Path to the image directory')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'stain':
        return 1
    else:
        return 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(), FLAGS.image_dir)
    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()

基于MobileNetV2-SSD缺陷检测
生成.pbtxt文件,内容为缺陷类别

三训练模型

1 下载fine-tune模型
2 修改参数
打开ssd_mobilenet_v2_coco.config,修改类别数目
基于MobileNetV2-SSD缺陷检测
3 fine-tune模型地址
基于MobileNetV2-SSD缺陷检测
4 修改数据集传输入口
基于MobileNetV2-SSD缺陷检测
4 cmd界面下执行python model_main.py --pipeline_config_path=training/ssdlite_mobilenet_v2_coco.config --model_dir=training --alsologtostder命令就可以开始训练了

四实验结果

生成checkpoint文件通过tensorboard --logdir=training查看
基于MobileNetV2-SSD缺陷检测
基于MobileNetV2-SSD缺陷检测

五表演真正技术时候到了

基于MobileNetV2-SSD缺陷检测

六 欢迎加我的github交流

本文地址:https://blog.csdn.net/weixin_42679015/article/details/107288438