侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python生成tensorflow输入输出的图像格式的方法

Python  /  管理员 发布于 7年前   293

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() 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    python web.py开发httpserver解决跨域问题实例解析
    下一条:
    python中数据爬虫requests库使用方法详解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客