自己写的制作 city的语义分割tfrecord  适用于deeplabv3+

自用

"""Converts PASCAL dataset to TFRecords file format."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import argparse
import io
import os
import sys
import natsort
import PIL.Image
import tensorflow as tf from utils import dataset_util parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='/home/a/dataset/cityscapes/',
help='Path to the directory containing the PASCAL VOC data.') parser.add_argument('--output_path', type=str, default='./dataset',
help='Path to the directory to create TFRecords outputs.') parser.add_argument('--train_data_list', type=str, default='./dataset/train.txt',
help='Path to the file listing the training data.') parser.add_argument('--valid_data_list', type=str, default='./dataset/val.txt',
help='Path to the file listing the validation data.') parser.add_argument('--image_data_dir', type=str, default='leftImg8bit',
help='The directory containing the image data.') parser.add_argument('--label_data_dir', type=str, default='gtFine',
help='The directory containing the augmented label data.') def dict_to_tf_example(image_path,
label_path):
"""Convert image and label to tf.Example proto. Args:
image_path: Path to a single PASCAL image.
label_path: Path to its corresponding label. Returns:
example: The converted tf.Example. Raises:
ValueError: if the image pointed to by image_path is not a valid JPEG or
if the label pointed to by label_path is not a valid PNG or
if the size of image does not match with that of label.
"""
with tf.gfile.GFile(image_path, 'rb') as fid:
encoded_jpg = fid.read()
encoded_jpg_io = io.BytesIO(encoded_jpg)
image = PIL.Image.open(encoded_jpg_io)
if image.format != 'PNG':
raise ValueError('Image format not PNG') with tf.gfile.GFile(label_path, 'rb') as fid:
encoded_label = fid.read()
encoded_label_io = io.BytesIO(encoded_label)
label = PIL.Image.open(encoded_label_io)
if label.format != 'PNG':
raise ValueError('Label format not PNG') if image.size != label.size:
raise ValueError('The size of image does not match with that of label.') width, height = image.size example = tf.train.Example(features=tf.train.Features(feature={
'image/height': dataset_util.int64_feature(height),
'image/width': dataset_util.int64_feature(width),
'image/encoded': dataset_util.bytes_feature(encoded_jpg),
'image/format': dataset_util.bytes_feature('png'.encode('utf8')),
'label/encoded': dataset_util.bytes_feature(encoded_label),
'label/format': dataset_util.bytes_feature('png'.encode('utf8')),
}))
return example
def scanDir_img_File(dir):
for root, dirs, files in os.walk(dir, True, None, False): # 遍列目录
for f in files:
yield os.path.join(root,f) def scanDir_lable_File(dir):
for root, dirs, files in os.walk(dir, True, None, False): # 遍列目录
# 处理该文件夹下所有文件: for f in files:
if os.path.isfile(os.path.join(root, f)):
a = os.path.splitext(f)
lable = a[0].split('_')[4]
# print(lable)
if lable in ('labelTrainIds'):
# print(os.path.join(root,f))
yield os.path.join(root,f) def create_tf_record(output_filename,
image_dir,
label_dir):
"""Creates a TFRecord file from examples. Args:
output_filename: Path to where output file is saved.
image_dir: Directory where image files are stored.
label_dir: Directory where label files are stored.
"""
imgg = []
writer = tf.python_io.TFRecordWriter(output_filename) img = scanDir_img_File(image_dir)
for imgs in img:
imgg.append(imgs)
image_list = natsort.natsorted(imgg) lable = scanDir_lable_File(label_dir)
lablee = []
for lables in lable:
lablee.append(lables)
label_list = natsort.natsorted(lablee)
for image_path,label_path in zip(image_list,label_list):
print(image_path,label_path)
try:
tf_example = dict_to_tf_example(image_path, label_path)
writer.write(tf_example.SerializeToString())
except ValueError:
tf.logging.warning('Invalid example: %s, ignoring.') writer.close() def main(unused_argv):
if not os.path.exists(FLAGS.output_path):
os.makedirs(FLAGS.output_path) tf.logging.info("Reading from CITY dataset")
train_image_dir = os.path.join(FLAGS.data_dir, FLAGS.image_data_dir,'train')
train_label_dir = os.path.join(FLAGS.data_dir, FLAGS.label_data_dir,'train')
val_image_dir = os.path.join(FLAGS.data_dir, FLAGS.image_data_dir, 'val')
val_label_dir = os.path.join(FLAGS.data_dir, FLAGS.label_data_dir, 'val') train_output_path = os.path.join(FLAGS.output_path, 'city_train.record')
val_output_path = os.path.join(FLAGS.output_path, 'city_val.record') create_tf_record(train_output_path, train_image_dir, train_label_dir)
create_tf_record(val_output_path, val_image_dir, val_label_dir) if __name__ == '__main__':
tf.logging.set_verbosity(tf.logging.INFO)
FLAGS, unparsed = parser.parse_known_args()
tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
 

Python 实现文件复制、删除的更多相关文章

  1. python之文件复制

    python文件复制操作. # -*- coding: utf-8 -*- import shutil import os # file_path = 'C:\\Users\\WT\\Desktop\ ...

  2. Java文件复制删除操作合集

    import java.io.*; public class FileOperate { public FileOperate() { } /** * 新建目录 * @param folderPath ...

  3. python之文件操作-复制、剪切、删除等

    以下是把sourceDir目录下的以.JPG结尾的文件所有拷贝到targetDir目录下: <span style="font-size:18px;">>> ...

  4. python中文件的复制

    python中文件的复制 python的os模块有很多文件目录相关的函数,但没有提供直接复制文件的函数,当然可以通过边都边写的方式复制文件.想要直接复制文件可以通过shutil模块 shutil模块是 ...

  5. Python 文件复制&按目录树结构拷贝&批量删除目录及其子目录下的文件

    文件复制&按目录树结构拷贝&批量删除目录及其子目录下的文件 by:授客 QQ:1033553122 测试环境: Python版本:Python 3.3.2 Win7 64 代码实践 # ...

  6. [WinAPI] API 9 [文件的删除、复制和移动功能]

    Windows系统为文件的删除.复制.重命名或移动文件提供了相应的API函数.删除文件使用DeleteFile函数:复制文件使用CopyFile函数:重命名文件和移动文件实际是一个操作,使用MoveF ...

  7. ASP FSO操作文件(复制文件、重命名文件、删除文件、替换字符串)

    ASP FSO操作文件(复制文件.重命名文件.删除文件.替换字符串)FSO的意思是FileSystemObject,即文件系统对象.FSO对象模型包含在Scripting 类型库 (Scrrun.Dl ...

  8. Python当前文件路径与文件夹删除操作

    前言: Python的文件操作跟Java存在部分差异.由于项目需要,近期使用python进行模块开发时遇到一些常见的文件操作便上网搜罗了一番,感觉众说纷纭.因此,结合自身的使用场景,贴一段python ...

  9. python实现某目录下将多个文件夹内的文件复制到一个文件夹中

    现实生活中,我们经常有这样的需求,如下图,有三个文件夹,文件夹1内含有1.txt文件 文件夹2中内含有2.txt文件,文件夹3中含有3.txt文件.我们有时候需要把1.txt, 2.txt, 3.tx ...

随机推荐

  1. Django基本视图

    Django基本视图 下面这三个类也许不能提供项目所需的所有的功能,这些应用于基于类的视图或Mixins情形下. 大多数Django的内建视图继承于其他基于类的视图或者各种mixins中,因为继承链是 ...

  2. Mybatis 系列7

    上篇系列6中 简单地给mybatis的配置画上了一个句号.那么从本篇文章开始,将会介绍mapper映射文件的配置. 这是mybatis的核心之一 一定要学好 在mapper文件中,以mapper作为根 ...

  3. Application "org.eclipse.ui.ide.workbench" could not be found in the registry.问题的解决

    今天升级Eclipse,升级完Restart,碰到启动不了让看日志,日志里主要错误信息即是Application "org.eclipse.ui.ide.workbench" co ...

  4. Ocelot中文文档-请求聚合

    Ocelot允许您指定聚合多个普通ReRoutes的Aggregate ReRoutes(聚合路由),并将其响应映射到一个对象中.一般用于当您有一个客户端向服务器发出多个请求,而这些请求可以合并成一个 ...

  5. SOFA 源码分析 — 负载均衡和一致性 Hash

    前言 SOFA 内置负载均衡,支持 5 种负载均衡算法,随机(默认算法),本地优先,轮询算法,一致性 hash,按权重负载轮询(不推荐,已被标注废弃). 一起看看他们的实现(重点还是一致性 hash) ...

  6. vue.js中的全局组件和局部组件

    组件(Component)是 Vue.js 最强大的功能之一.组件可以扩展 HTML 元素,封装可重用的代码.在较高层面上,组件是自定义元素, Vue.js 的编译器为它添加特殊功能. 组件的使用有三 ...

  7. ArcEngine小问题解决

    最近开始使用VS2012,在引用COM组件的时候,出现了无法嵌入互操作类型“……”,请改用适用的接口的错误提示. 找到解决方案:选中项目中引入的dll,鼠标右键,选择属性,把“嵌入互操作类型”设置为F ...

  8. Java父类对象调用子类实体:方法重写与动态调用

    众所周知Java的handle和C++的ponter而不是object对应,我们很熟悉C++的父类pointer调用子类实体的例子,那么对于Java的handle是不是也可以这样呢? 这里我先给一个例 ...

  9. C#System.Text.RegularExpressions.Regex使用(二) .

    (6)特殊字符的匹配 string x = "//"; Regex r1 = new Regex("^////$"); Console.WriteLine(&q ...

  10. python 基础(四) 正则,递归 生成器

    字符串是编程时涉及到的最多的一种数据结构,对字符串进行操作的需求几乎无处不在.比如判断一个字符串是否是合法的Email地址,虽然可以编程提取@前后的子串,再分别判断是否是单词和域名,但这样做不但麻烦, ...