簡體   English   中英

生成 tf_record 時出錯:AttributeError: module 'tensorflow' has no attribute 'app'

[英]Error when generating tf_record: AttributeError: module 'tensorflow' has no attribute 'app'

我正在嘗試按照教程使用 Tensorflow 創建對象檢測算法。 基本上,當我嘗試生成 tfrecord 並將其放入我的數據文件夾時,出現錯誤。 詳情如下。 作為旁注,我使用的是Python 3.7.8

使用Labelimg軟件標記我的圖像后,我在桌面目錄中創建了三個文件夾,分別名為“data”、“images”和“training”。在images文件夾中,有兩個子文件夾,分別稱為“test”和“train” .” 在以 PascalVOC 格式(.xml 文件輸出)標記我的圖像后,我將圖像分別移動到“test”和“train”文件夾中。

我首先使用以下代碼將 xml 文件轉換為 csv 文件,該代碼作為 xml_to_csv.py 保存到我的目錄中:

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():
    for directory in ['train','test']:
        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
        xml_df = xml_to_csv(image_path)
        xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')


main()

運行 anaconda 提示命令python xml_to_csv.py在我的“數據”文件夾中生成兩個 CSV 文件,其中訓練樣本的格式正確。

現在,使用以下代碼,我需要使用以下代碼為訓練和測試文件生成 tf_record。 我只有一門課,“雜草”,已在下面編輯。 python 文件被保存為 generate_tfrecord.py。

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')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('image_dir', '', 'Path to images')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'weed':
        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(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()

在 anaconda 命令提示符下,運行命令python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=data/test.record --image_dir=images/會產生以下錯誤:

2020-10-15 11:20:43.224624: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-10-15 11:20:43.226712: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "generate_tfrecord.py", line 22, in <module>
    flags = tf.app.flags
AttributeError: module 'tensorflow' has no attribute 'app'

我該如何解決這個問題,以便我可以創建 tfrecord 文件以直接放入我的“數據”文件夾中?

tensorflow.app在最新的 tensorflow 中不可用

嘗試更換

flags = tf.app.flags with flags = tf.compat.v1.flags (第 14 行)

writer = tf.python_io.TFRecordWriter(FLAGS.output_path)writer = tf.io.TFRecordWriter(FLAGS.output_path) (第 77 行)

tf.app.run()tf.compat.v1.app.run() (最后一行)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM