1. 程式人生 > >Tensorflow之構建自己的圖片資料集TFrecords

Tensorflow之構建自己的圖片資料集TFrecords

   學習谷歌的深度學習終於有點眉目了,給大家分享我的Tensorflow學習歷程。

   tensorflow的官方中文文件比較生澀,資料集一直採用的MNIST二進位制資料集。並沒有過多講述怎麼構建自己的圖片資料集tfrecords。

   先貼我的轉化程式碼將圖片資料夾下的圖片轉存tfrecords的資料集。

############################################################################################
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#Author  : zhaoqinghui
#Date    : 2016.5.10
#Function: image convert to tfrecords 
#############################################################################################

import tensorflow as tf
import numpy as np
import cv2
import os
import os.path
from PIL import Image

#引數設定
###############################################################################################
train_file = 'train.txt' #訓練圖片
name='train'      #生成train.tfrecords
output_directory='./tfrecords'
resize_height=32 #儲存圖片高度
resize_width=32 #儲存圖片寬度
###############################################################################################
def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def load_file(examples_list_file):
    lines = np.genfromtxt(examples_list_file, delimiter=" ", dtype=[('col1', 'S120'), ('col2', 'i8')])
    examples = []
    labels = []
    for example, label in lines:
        examples.append(example)
        labels.append(label)
    return np.asarray(examples), np.asarray(labels), len(lines)

def extract_image(filename,  resize_height, resize_width):
    image = cv2.imread(filename)
    image = cv2.resize(image, (resize_height, resize_width))
    b,g,r = cv2.split(image)       
    rgb_image = cv2.merge([r,g,b])     
    return rgb_image

def transform2tfrecord(train_file, name, output_directory, resize_height, resize_width):
    if not os.path.exists(output_directory) or os.path.isfile(output_directory):
        os.makedirs(output_directory)
    _examples, _labels, examples_num = load_file(train_file)
    filename = output_directory + "/" + name + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(filename)
    for i, [example, label] in enumerate(zip(_examples, _labels)):
        print('No.%d' % (i))
        image = extract_image(example, resize_height, resize_width)
        print('shape: %d, %d, %d, label: %d' % (image.shape[0], image.shape[1], image.shape[2], label))
        image_raw = image.tostring()
        example = tf.train.Example(features=tf.train.Features(feature={
            'image_raw': _bytes_feature(image_raw),
            'height': _int64_feature(image.shape[0]),
            'width': _int64_feature(image.shape[1]),
            'depth': _int64_feature(image.shape[2]),
            'label': _int64_feature(label)
        }))
        writer.write(example.SerializeToString())
    writer.close()

def disp_tfrecords(tfrecord_list_file):
    filename_queue = tf.train.string_input_producer([tfrecord_list_file])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
 features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'height': tf.FixedLenFeature([], tf.int64),
          'width': tf.FixedLenFeature([], tf.int64),
          'depth': tf.FixedLenFeature([], tf.int64),
          'label': tf.FixedLenFeature([], tf.int64)
      }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    #print(repr(image))
    height = features['height']
    width = features['width']
    depth = features['depth']
    label = tf.cast(features['label'], tf.int32)
    init_op = tf.initialize_all_variables()
    resultImg=[]
    resultLabel=[]
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess=sess, coord=coord)
        for i in range(21):
            image_eval = image.eval()
            resultLabel.append(label.eval())
            image_eval_reshape = image_eval.reshape([height.eval(), width.eval(), depth.eval()])
            resultImg.append(image_eval_reshape)
            pilimg = Image.fromarray(np.asarray(image_eval_reshape))
            pilimg.show()
        coord.request_stop()
        coord.join(threads)
        sess.close()
    return resultImg,resultLabel

def read_tfrecord(filename_queuetemp):
    filename_queue = tf.train.string_input_producer([filename_queuetemp])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
          'image_raw': tf.FixedLenFeature([], tf.string),
          'width': tf.FixedLenFeature([], tf.int64),
          'depth': tf.FixedLenFeature([], tf.int64),
          'label': tf.FixedLenFeature([], tf.int64)
      }
    )
    image = tf.decode_raw(features['image_raw'], tf.uint8)
    # image
    tf.reshape(image, [256, 256, 3])
    # normalize
    image = tf.cast(image, tf.float32) * (1. /255) - 0.5
    # label
    label = tf.cast(features['label'], tf.int32)
    return image, label

def test():
    transform2tfrecord(train_file, name , output_directory,  resize_height, resize_width) #轉化函式   
    img,label=disp_tfrecords(output_directory+'/'+name+'.tfrecords') #顯示函式
    img,label=read_tfrecord(output_directory+'/'+name+'.tfrecords') #讀取函式
    print label

if __name__ == '__main__':
    test()


這樣就可以得到自己專屬的資料集.tfrecords了  ,它可以直接用於tensorflow的資料集。

相關推薦

Tensorflow構建自己圖片資料TFrecords(精)

用了這麼久的tensorflow,例子跑了N多便,基本流程是清楚了。但是自己獨立做一個小例子各種問題都來了。如自己圖片資料集怎麼做?說句老實話,tensorflow真是煩,管方文件教程上老拿MNIST和cifar_10這種做好的資料集說事,對於我們這些初學者,完

Tensorflow構建自己圖片資料TFrecords

   學習谷歌的深度學習終於有點眉目了,給大家分享我的Tensorflow學習歷程。    tensorflow的官方中文文件比較生澀,資料集一直採用的MNIST二進位制資料集。並沒有過多講述怎麼構建自己的圖片資料集tfrecords。    先貼我的轉化程式碼將圖片資料夾

Tensorflow構建自己圖片資料TFrecords(二)

    分類好了圖片,接下來製作成Tfrecord格式。    先貼程式碼:import tensorflow as tf from PIL import Image import os cwd = os.getcwd() root = cwd+"./images_vari

Tensorflow構建自己圖片資料

用了這麼久的tensorflow,例子跑了N多便,基本流程是清楚了。但是自己獨立做一個小例子各種問題都來了。如自己圖片資料集怎麼做?說句老實話,tensorflow真是煩,管方文件教程上老拿MNIST和cifar_10這種做好的資料集說事,對於我們這些初學者,完全不知道圖片該

SSD講堂五(訓練) SSD Tensorflow 訓練測試自己資料 Jupiter notebook 顯示訓練結果 原博主:Echo_Harrington

關於訓練的部落格: https://blog.csdn.net/echo_harrington/article/details/81131441 關於統計目標框個數的程式碼(上述連結的統計程式碼有問題,此博主對其進行了修改): https://blog.csdn.net/memories

完整實現利用tensorflow訓練自己圖片資料

經過差不多一個禮拜的時間的學習,終於把完整的一個利用自己爬取的圖片做訓練資料集的卷積神經網路的實現(基於tensorflow)   簡單整理一下思路: 獲取資料集(上網爬取,或者直接找公開的圖片資料集) reshape圖片成相同大小(公開資料集一般都是相同sha

使用TFRecord進行圖片格式轉換以及搭建神經網路實驗全過程,使用Tensorflow訓練自己資料

最近一個大作業需要進行影象處理可是網上的資源太分散,於是想整合網上資源,形成一個系統: 主要包括 圖片預處理 圖片轉TFrecord格式 TFrecord格式轉圖片檢視 簡單神經網路搭建 TFrecord格式在神經網路中的讀取 batch方法提取資料

基於tensorflow 批量修改自己圖片資料 (附程式碼)

       現在網上有很多關於Deeplearning的教程,不過這些教程的資料集都是已經做好的,並且格式名字什麼的都已經整理好了。特別是很多入門的教程都是Mnist 的資料集,這都已經非常的完善了。不過對於想自己製作資料集的小白來說,如何將自己收集的圖片批量轉換為自己需要

利用tensorflow訓練自己圖片資料——資料準備

昨天實現了一個簡單的CNN網路。用了MNIST資料集,雖然看來對這個資料集用的很多,但是真正這個資料集是怎麼在訓練的時候被呼叫的,以及怎麼把它換成自己的資料集都是一臉懵。 作者給的程式碼是python2.x版本的,我用的python3.5,改了一些錯誤。 import

SSD Tensorflow訓練自己資料,遇到報錯absl.flags._exceptions.IllegalFlagValueError: flag --num_classes==: 求助

按照此部落格訓練到“五.訓練”這一步報錯。 連結:https://blog.csdn.net/Echo_Harrington/article/details/81131441   下面是bash 的   train.sh  檔案博主給的內容 D

使用tensorflow訓練自己資料(一)——製作資料

使用tensorflow訓練自己的資料集—製作資料集 想記錄一下自己製作訓練集並訓練的過、希望踩過的坑能幫助後面入坑的人。 本次使用的訓練集的是kaggle中經典的貓狗大戰資料集(提取碼:ufz5)。因為本人筆記本配置很差還不是N卡所以把train的資料分成了訓練集和測試集並沒有使用

使用tensorflow訓練自己資料(四)——計算模型準確率

使用tensorflow訓練自己的資料集—定義反向傳播 上一篇使用tensorflow訓練自己的資料集(三)中製作已經介紹了定義反向傳播過程來訓練神經網路,訓練完神經網路後應對神經網路進行準確率的計算。 import time import forward import back

tensorflow】Object DetectionAPI訓練識別自己資料

#一、資料準備 ###1.一個友好的標註工具 各種系統安裝已經再此介紹的很詳細了,linux下可以三行命令解決。 注意:圖片要求是png或者jpg格式 1> . 標註資訊存為xml檔案,使用該指令碼可以將所有的xml檔案轉換為1個csv檔案(自行修改xml路徑

sklearn 學習實踐——基於自帶資料(波士頓房價、鳶尾花、糖尿病等)構建分類、迴歸模型

      只要是接觸機器學習的,很少有沒聽過sklearn的,這個真的可以稱得上是機器學習快速進行的神器了,在研究生的時候搭建常用的機器學習模型用的就是sklearn,今天應部門的一些需求,簡單的總結了一點使用方法,後面還會繼續更新,今天僅使用sklearn自帶的資料

使用tensorflow訓練自己資料(一)

使用tensorflow訓練自己的資料集 想記錄一下自己製作訓練集並訓練的過、希望踩過的坑能幫助後面入坑的人。 本次使用的訓練集的是kaggle中經典的貓狗大戰資料集(提取碼:ufz5)。因為本人筆記本配置很差還不是N卡所以把train的資料分成了訓練集和測試集

使用tensorflow訓練自己資料(二)

使用tensorflow訓練自己的資料集—定義神經網路 上一篇使用tensorflow訓練自己的資料集(一)中製作已經介紹了製作自己的資料集、接下來就是定義向前傳播過程了也就是定義神經網路。本次使用了兩層卷積兩層最大池化兩層全連線神經網路最後加softmax層的

使用tensorflow訓練自己資料(三)——定義反向傳播過程

使用tensorflow訓練自己的資料集—定義反向傳播 上一篇使用tensorflow訓練自己的資料集(二)中製作已經介紹了定義神經網路、接下來就是定義反向傳播過程進行訓練神經網路了。反向傳播過程中使用了滑動平均類和學習率指數下降來優化神經網路。 ps.沒有GP

深度學習(二)——從零自己製作資料到利用deepNN實現誇張人臉表情的實時監測(tensorflow實現)

一、背景介紹 這篇文章主要參考我的上一篇文章:深度學習(一)——deepNN模型實現攝像頭實時識別人臉表情(C++和python3.6混合程式設計)。由於上一篇文章的模型所採用的資料集為fer2013,前面也介紹過這個基於這個資料集的模型識別人臉表情的準確率大概在70%左右

TensorFlow詳解貓狗識別(一)--讀取自己資料

資料集下載 連結: https://pan.baidu.com/s/1SlNAPf3NbgPyf93XluM7Fg 密碼: hpn4 資料集分別有12500張cat,12500張dog 讀取資料集 資料集的讀取,查閱了那麼多文件,大致瞭解到,資料集的讀取方法大概會分為兩種

Mask R-CNN訓練自己資料在win10上的踩坑全過程:CUDA9.0+CUDNN7.1.4+Tensorflow-gpu1.9.0+keras-gpu2.2.4

基礎配置 首先你需要在win10上下載Git(用於我們在github上面下載原始碼)和MinGW(方便我們在win10上也能用linux的make操作命令)。 接著你要下載cuda9.0和cudnn7.1來繫結你的windows的Nvidia 接著你需要在win10上面安裝an