python生成tensorflow输入输出的图像格式的方法
作者:何雷 发布时间:2021-03-20 05:21:08
标签:tensorflow,输入,输出
TensorFLow能够识别的图像文件,可以通过numpy,使用tf.Variable或者tf.placeholder加载进tensorflow;也可以通过自带函数(tf.read)读取,当图像文件过多时,一般使用pipeline通过队列的方法进行读取。下面我们介绍两种生成tensorflow的图像格式的方法,供给tensorflow的graph的输入与输出。
import cv2
import numpy as np
import h5py
height = 460
width = 345
with h5py.File('make3d_dataset_f460.mat','r') as f:
images = f['images'][:]
image_num = len(images)
data = np.zeros((image_num, height, width, 3), np.uint8)
data = images.transpose((0,3,2,1))
先生成图像文件的路径:ls *.jpg> list.txt
import cv2
import numpy as np
image_path = './'
list_file = 'list.txt'
height = 48
width = 48
image_name_list = [] # read image
with open(image_path + list_file) as fid:
image_name_list = [x.strip() for x in fid.readlines()]
image_num = len(image_name_list)
data = np.zeros((image_num, height, width, 3), np.uint8)
for idx in range(image_num):
img = cv2.imread(image_name_list[idx])
img = cv2.resize(img, (height, width))
data[idx, :, :, :] = img
2 Tensorflow自带函数读取
def get_image(image_path):
"""Reads the jpg image from image_path.
Returns the image as a tf.float32 tensor
Args:
image_path: tf.string tensor
Reuturn:
the decoded jpeg image casted to float32
"""
return tf.image.convert_image_dtype(
tf.image.decode_jpeg(
tf.read_file(image_path), channels=3),
dtype=tf.uint8)
pipeline读取方法
# Example on how to use the tensorflow input pipelines. The explanation can be found here ischlag.github.io.
import tensorflow as tf
import random
from tensorflow.python.framework import ops
from tensorflow.python.framework import dtypes
dataset_path = "/path/to/your/dataset/mnist/"
test_labels_file = "test-labels.csv"
train_labels_file = "train-labels.csv"
test_set_size = 5
IMAGE_HEIGHT = 28
IMAGE_WIDTH = 28
NUM_CHANNELS = 3
BATCH_SIZE = 5
def encode_label(label):
return int(label)
def read_label_file(file):
f = open(file, "r")
filepaths = []
labels = []
for line in f:
filepath, label = line.split(",")
filepaths.append(filepath)
labels.append(encode_label(label))
return filepaths, labels
# reading labels and file path
train_filepaths, train_labels = read_label_file(dataset_path + train_labels_file)
test_filepaths, test_labels = read_label_file(dataset_path + test_labels_file)
# transform relative path into full path
train_filepaths = [ dataset_path + fp for fp in train_filepaths]
test_filepaths = [ dataset_path + fp for fp in test_filepaths]
# for this example we will create or own test partition
all_filepaths = train_filepaths + test_filepaths
all_labels = train_labels + test_labels
all_filepaths = all_filepaths[:20]
all_labels = all_labels[:20]
# convert string into tensors
all_images = ops.convert_to_tensor(all_filepaths, dtype=dtypes.string)
all_labels = ops.convert_to_tensor(all_labels, dtype=dtypes.int32)
# create a partition vector
partitions = [0] * len(all_filepaths)
partitions[:test_set_size] = [1] * test_set_size
random.shuffle(partitions)
# partition our data into a test and train set according to our partition vector
train_images, test_images = tf.dynamic_partition(all_images, partitions, 2)
train_labels, test_labels = tf.dynamic_partition(all_labels, partitions, 2)
# create input queues
train_input_queue = tf.train.slice_input_producer(
[train_images, train_labels],
shuffle=False)
test_input_queue = tf.train.slice_input_producer(
[test_images, test_labels],
shuffle=False)
# process path and string tensor into an image and a label
file_content = tf.read_file(train_input_queue[0])
train_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
train_label = train_input_queue[1]
file_content = tf.read_file(test_input_queue[0])
test_image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS)
test_label = test_input_queue[1]
# define tensor shape
train_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])
test_image.set_shape([IMAGE_HEIGHT, IMAGE_WIDTH, NUM_CHANNELS])
# collect batches of images before processing
train_image_batch, train_label_batch = tf.train.batch(
[train_image, train_label],
batch_size=BATCH_SIZE
#,num_threads=1
)
test_image_batch, test_label_batch = tf.train.batch(
[test_image, test_label],
batch_size=BATCH_SIZE
#,num_threads=1
)
print "input pipeline ready"
with tf.Session() as sess:
# initialize the variables
sess.run(tf.initialize_all_variables())
# initialize the queue threads to start to shovel data
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
print "from the train set:"
for i in range(20):
print sess.run(train_label_batch)
print "from the test set:"
for i in range(10):
print sess.run(test_label_batch)
# stop our queue threads and properly close the session
coord.request_stop()
coord.join(threads)
sess.close()
来源:http://blog.csdn.net/helei001/article/details/51354404


猜你喜欢
- 1.贴题题目来自PythonTip 信息加密给你个小写英文字符串a和一个非负数b(0<=b<26), 将a中的每个小写字符替换成
- 打开文件操作文件1打开文件时,需要指定文件路径和打开方式打开方式:r:只读w:只写a:追加“+”表示可以同时读写某个文件r+:读写w+:写读
- 常有人因为页面的面积问题,想在一个窄小的地方,显示一条条的信息,顺序往上滚动,在经典的BBS里,有一个随机上滚动的JS,好些人用不了,现在蛋
- 一、super( ) 的用途了解 super() 函数之前,我们首先要知道 super() 的用途是啥?主要用来在子类中调用父类的方法。多用
- 我们知道,关系型数据一般以规范化的形式保存,也就是说你应该尽可能少地重复数据;在正常情况下,表与表之间仅通过各种键值实现关联。进一步地讲,规
- pyinstaller 属于Python第三方库,使用前需先安装# 首先安装pyinstallerpip install pyinstall
- 前面简单介绍了Python列表基本操作,这里再来简单讲述一下Python元组相关操作>>> dir(tuple) #查看元
- 在SQL SERVER中如何通过SQL语句获取服务器硬件和系统信息呢?下面介绍一下如何通过SQL语句获取处理器(CPU)、内存(Memory
- 一、概念1. Pinia => PiniaPinia(发音为/pi?nj?/,如英语中的“pe
- Math.random()Math.random()是JavaScript默认提供的生成随机数的方法。该方法返回一个0到1之间的浮点数,其值
- 一、Node.js实现代码var http = require('http');var util = require(
- 本文实例讲述了python数组过滤实现方法。分享给大家供大家参考。具体如下:这段代码可以按照指定的条件过滤数组内的元素,返回过滤后的数组li
- 导入模块import configparser # py3写入config = configparser.ConfigParser()con
- 最近项目中遇见 Jquery Ajax 缓存问题,load出来的页面状态有时正常,有时不对,记录一下,希望对大家有帮助使用jquery里lo
- 出自:【孟宪会之精彩世界】 发布日期:2005年1月27日 8点48分0秒 [有删改] 由于某些原
- 随着网络的发展,人们通过各种方式使用它。今天,网络购物,跟朋友或者不认识的人聊天,管理银行账户,以及一些日常应用,共享照片或视频,等等。事实
- 相信大家在日常的开发中经常会碰到榜单类的活动需求,通常在榜单中都会要求返回排名,今天我们就用MySQL的窗口函数来快速实现一下首先,先建一个
- 队列(queue)队列是先进先出(FIFO, First-In-First-Out)的线性表,在具体应用中通常用链表或者数组来实现,队列只允
- 四种基本的函数类型局部变量 就是在函数内部定义的变量【作用域仅局限于函数内部】不同的函数 可以定义相同的局部变量,但是各自用各自的 不会产生
- 本文实例讲述了JS实现带鼠标效果的头像及文章列表代码。分享给大家供大家参考。具体如下:这是一种带图片功能的文章或新闻列表功能,鼠标滑过标题列