最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談TensorFlow中讀取圖像數(shù)據(jù)的三種方式

 更新時(shí)間:2020年06月30日 08:32:24   作者:PRO_Z  
這篇文章主要介紹了淺談TensorFlow中讀取圖像數(shù)據(jù)的三種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

 本文面對(duì)三種常常遇到的情況,總結(jié)三種讀取數(shù)據(jù)的方式,分別用于處理單張圖片、大量圖片,和TFRecorder讀取方式。并且還補(bǔ)充了功能相近的tf函數(shù)。

1、處理單張圖片

  我們訓(xùn)練完模型之后,常常要用圖片測(cè)試,有的時(shí)候,我們并不需要對(duì)很多圖像做測(cè)試,可能就是幾張甚至一張。這種情況下沒有必要用隊(duì)列機(jī)制。

import tensorflow as tf
import matplotlib.pyplot as plt

def read_image(file_name):
 img = tf.read_file(filename=file_name)  # 默認(rèn)讀取格式為uint8
 print("img 的類型是",type(img));
 img = tf.image.decode_jpeg(img,channels=0) # channels 為1得到的是灰度圖,為0則按照?qǐng)D片格式來讀
 return img

def main( ):
 with tf.device("/cpu:0"):
      # img_path是文件所在地址包括文件名稱,地址用相對(duì)地址或者絕對(duì)地址都行 
   img_path='./1.jpg'
   img=read_image(img_path)
   with tf.Session() as sess:
   image_numpy=sess.run(img)
   print(image_numpy)
   print(image_numpy.dtype)
   print(image_numpy.shape)
   plt.imshow(image_numpy)
   plt.show()

if __name__=="__main__":
 main()

"""

輸出結(jié)果為:

img 的類型是 <class 'tensorflow.python.framework.ops.Tensor'>
[[[196 219 209]
  [196 219 209]
  [196 219 209]
  ...

 [[ 71 106  42]
  [ 59  89  39]
  [ 34  63  19]
  ...
  [ 21  52  46]
  [ 15  45  43]
  [ 22  50  53]]]
uint8
(675, 1200, 3)
"""

   和tf.read_file用法相似的函數(shù)還有tf.gfile.FastGFile  tf.gfile.GFile,只是要指定讀取方式是'r' 還是'rb' 。

2、需要讀取大量圖像用于訓(xùn)練

  這種情況就需要使用Tensorflow隊(duì)列機(jī)制。首先是獲得每張圖片的路徑,把他們都放進(jìn)一個(gè)list里面,然后用string_input_producer創(chuàng)建隊(duì)列,再用tf.WholeFileReader讀取。具體請(qǐng)看下例:

def get_image_batch(data_file,batch_size):
 data_names=[os.path.join(data_file,k) for k in os.listdir(data_file)]
 
 #這個(gè)num_epochs函數(shù)在整個(gè)Graph是local Variable,所以在sess.run全局變量的時(shí)候也要加上局部變量。 
 filenames_queue=tf.train.string_input_producer(data_names,num_epochs=50,shuffle=True,capacity=512)
 reader=tf.WholeFileReader()
 _,img_bytes=reader.read(filenames_queue)
 image=tf.image.decode_png(img_bytes,channels=1) #讀取的是什么格式,就decode什么格式
 #解碼成單通道的,并且獲得的結(jié)果的shape是[?, ?,1],也就是Graph不知道圖像的大小,需要set_shape
 image.set_shape([180,180,1]) #set到原本已知圖像的大小?;蛘咧苯油ㄟ^tf.image.resize_images,tf.reshape()
 image=tf.image.convert_image_dtype(image,tf.float32)
 #預(yù)處理 下面的一句代碼可以換成自己想使用的預(yù)處理方式
 #image=tf.divide(image,255.0) 
 return tf.train.batch([image],batch_size) 

  這里的date_file是指文件夾所在的路徑,不包括文件名。第一句是遍歷指定目錄下的文件名稱,存放到一個(gè)list中。當(dāng)然這個(gè)做法有很多種方法,比如glob.glob,或者tf.train.match_filename_once

全部代碼如下:

import tensorflow as tf
import os
def read_image(data_file,batch_size):
 data_names=[os.path.join(data_file,k) for k in os.listdir(data_file)]
 filenames_queue=tf.train.string_input_producer(data_names,num_epochs=5,shuffle=True,capacity=30)
 reader=tf.WholeFileReader()
 _,img_bytes=reader.read(filenames_queue)
 image=tf.image.decode_jpeg(img_bytes,channels=1)
 image=tf.image.resize_images(image,(180,180))

 image=tf.image.convert_image_dtype(image,tf.float32)
 return tf.train.batch([image],batch_size)

def main( ):
 img_path=r'F:\dataSet\WIDER\WIDER_train\images\6--Funeral' #本地的一個(gè)數(shù)據(jù)集目錄,有足夠的圖像
 img=read_image(img_path,batch_size=10)
 image=img[0] #取出每個(gè)batch的第一個(gè)數(shù)據(jù)
 print(image)
 init=[tf.global_variables_initializer(),tf.local_variables_initializer()]
 with tf.Session() as sess:
  sess.run(init)
  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(sess=sess,coord=coord)
  try:
   while not coord.should_stop():
    print(image.shape)
  except tf.errors.OutOfRangeError:
   print('read done')
  finally:
   coord.request_stop()
  coord.join(threads)


if __name__=="__main__":
 main()

"""

輸出如下:

(180, 180, 1)
(180, 180, 1)
(180, 180, 1)
(180, 180, 1)
(180, 180, 1)
"""

  這段代碼可以說寫的很是規(guī)整了。注意到init里面有對(duì)local變量的初始化,并且因?yàn)橛玫搅岁?duì)列,當(dāng)然要告訴電腦什么時(shí)候隊(duì)列開始, tf.train.Coordinator 和 tf.train.start_queue_runners 就是兩個(gè)管理隊(duì)列的類,用法如程序所示。

  與 tf.train.string_input_producer相似的函數(shù)是 tf.train.slice_input_producer。 tf.train.slice_input_producer和tf.train.string_input_producer的第一個(gè)參數(shù)形式不一樣。等有時(shí)間再做一個(gè)二者比較的博客

 3、對(duì)TFRecorder解碼獲得圖像數(shù)據(jù)

  其實(shí)這塊和上一種方式差不多的,更重要的是怎么生成TFRecorder文件,這一部分我會(huì)補(bǔ)充到另一篇博客上。

  仍然使用 tf.train.string_input_producer。

import tensorflow as tf
import matplotlib.pyplot as plt
import os
import cv2
import numpy as np
import glob

def read_image(data_file,batch_size):
 files_path=glob.glob(data_file)
 queue=tf.train.string_input_producer(files_path,num_epochs=None)
 reader = tf.TFRecordReader()
 print(queue)
 _, serialized_example = reader.read(queue)
 features = tf.parse_single_example(
  serialized_example,
  features={
   'image_raw': tf.FixedLenFeature([], tf.string),
   'label_raw': tf.FixedLenFeature([], tf.string),
  })
 image = tf.decode_raw(features['image_raw'], tf.uint8)
 image = tf.cast(image, tf.float32)
 image.set_shape((12*12*3))
 label = tf.decode_raw(features['label_raw'], tf.float32)
 label.set_shape((2))
 # 預(yù)處理部分省略,大家可以自己根據(jù)需要添加
 return tf.train.batch([image,label],batch_size=batch_size,num_threads=4,capacity=5*batch_size)

def main( ):
 img_path=r'F:\python\MTCNN_by_myself\prepare_data\pnet*.tfrecords' #本地的幾個(gè)tf文件
 img,label=read_image(img_path,batch_size=10)
 image=img[0]
 init=[tf.global_variables_initializer(),tf.local_variables_initializer()]
 with tf.Session() as sess:
  sess.run(init)
  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(sess=sess,coord=coord)
  try:
   while not coord.should_stop():
    print(image.shape)
  except tf.errors.OutOfRangeError:
   print('read done')
  finally:
   coord.request_stop()
  coord.join(threads)


if __name__=="__main__":
 main()

  在read_image函數(shù)中,先使用glob函數(shù)獲得了存放tfrecord文件的列表,然后根據(jù)TFRecord文件是如何存的就如何parse,再set_shape;這里有必要提醒下parse的方式。我們看到這里用的是tf.decode_raw ,因?yàn)樽鯰FRecord是將圖像數(shù)據(jù)string化了,數(shù)據(jù)是串行的,丟失了空間結(jié)果。從features中取出image和label的數(shù)據(jù),這時(shí)就要用 tf.decode_raw  解碼,得到的結(jié)果當(dāng)然也是串行的了,所以set_shape 成一個(gè)串行的,再reshape。這種方式是取決于你的編碼TFRecord方式的。

再舉一種例子:

reader=tf.TFRecordReader()
_,serialized_example=reader.read(file_name_queue)
features = tf.parse_single_example(serialized_example, features={
 'data': tf.FixedLenFeature([256,256], tf.float32), ###
 'label': tf.FixedLenFeature([], tf.int64),
 'id': tf.FixedLenFeature([], tf.int64)
})
img = features['data']
label =features['label']
id = features['id']

  這個(gè)時(shí)候就不需要任何解碼了。因?yàn)樽鯰FRecord的方式就是直接把圖像數(shù)據(jù)append進(jìn)去了。

參考鏈接:

  https://blog.csdn.net/qq_34914551/article/details/86286184

到此這篇關(guān)于淺談TensorFlow中讀取圖像數(shù)據(jù)的三種方式的文章就介紹到這了,更多相關(guān)TensorFlow 讀取圖像數(shù)據(jù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python opencv實(shí)現(xiàn)圖像配準(zhǔn)與比較

    python opencv實(shí)現(xiàn)圖像配準(zhǔn)與比較

    這篇文章主要為大家詳細(xì)介紹了python opencv實(shí)現(xiàn)圖像配準(zhǔn)與比較,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-02-02
  • 使用matlab或python將txt文件轉(zhuǎn)為excel表格

    使用matlab或python將txt文件轉(zhuǎn)為excel表格

    這篇文章主要介紹了matlab或python代碼將txt文件轉(zhuǎn)為excel表格,本文通過matlab代碼和python 代碼給大家詳細(xì)介紹,需要的朋友可以參考下
    2019-11-11
  • Python將Office文檔(Word、Excel、PDF、PPT)轉(zhuǎn)為OFD格式的實(shí)現(xiàn)方法

    Python將Office文檔(Word、Excel、PDF、PPT)轉(zhuǎn)為OFD格式的實(shí)現(xiàn)方法

    OFD(Open Fixed-layout Document )是我國(guó)自主制定的一種開放版式文件格式標(biāo)準(zhǔn),如果想要通過Python將Office文檔(如Word、Excel或PowerPoint)及PDF文檔轉(zhuǎn)換為OFD格式,可以參考本文中提供的實(shí)現(xiàn)方法,需要的朋友可以參考下
    2024-06-06
  • Python如何讀取、寫入JSON數(shù)據(jù)

    Python如何讀取、寫入JSON數(shù)據(jù)

    這篇文章主要介紹了Python如何讀取、寫入JSON數(shù)據(jù),文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下
    2020-07-07
  • 淺談python中常用的excel模塊庫(kù)

    淺談python中常用的excel模塊庫(kù)

    本文主要介紹了python中常用的excel模塊庫(kù),感興趣的同學(xué),可以參考下。
    2021-06-06
  • Python 實(shí)現(xiàn)毫秒級(jí)淘寶搶購(gòu)腳本的示例代碼

    Python 實(shí)現(xiàn)毫秒級(jí)淘寶搶購(gòu)腳本的示例代碼

    本篇文章主要介紹了Python 通過selenium實(shí)現(xiàn)毫秒級(jí)自動(dòng)搶購(gòu)的示例代碼,通過掃碼登錄即可自動(dòng)完成一系列操作,搶購(gòu)時(shí)間精確至毫秒,可搶加購(gòu)物車等待時(shí)間結(jié)算的,感興趣的小伙伴們可以參考一下
    2019-09-09
  • Python實(shí)用庫(kù) PrettyTable 學(xué)習(xí)筆記

    Python實(shí)用庫(kù) PrettyTable 學(xué)習(xí)筆記

    這篇文章主要介紹了Python實(shí)用庫(kù) PrettyTable 學(xué)習(xí)筆記,結(jié)合實(shí)例形式分析了Python表格操作庫(kù)PrettyTable的安裝、使用技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下
    2019-08-08
  • Python包和模塊的分發(fā)詳細(xì)介紹

    Python包和模塊的分發(fā)詳細(xì)介紹

    這篇文章主要介紹了Python包和模塊的分發(fā),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-06-06
  • python flask 如何修改默認(rèn)端口號(hào)的方法步驟

    python flask 如何修改默認(rèn)端口號(hào)的方法步驟

    這篇文章主要介紹了python flask 如何修改默認(rèn)端口號(hào)的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例

    Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例

    這篇文章主要介紹了Django結(jié)合使用Scrapy爬取數(shù)據(jù)入庫(kù)的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評(píng)論

双流县| 开鲁县| 防城港市| 图木舒克市| 宝坻区| 临江市| 崇明县| 任丘市| 隆德县| 莫力| 察哈| 金平| 兴仁县| 灵川县| 宜州市| 苍山县| 邢台市| 广饶县| 饶阳县| 西乡县| 荣成市| 龙口市| 长葛市| 清涧县| 东方市| 景谷| 大埔区| 织金县| 固安县| 岳西县| 南溪县| 德令哈市| 南宫市| 穆棱市| 安吉县| 长垣县| 康马县| 新绛县| 黑山县| 宁城县| 西贡区|