對python制作自己的數(shù)據(jù)集實例講解
一、數(shù)據(jù)集介紹
點擊打開鏈接17_Category_Flower 是一個不同種類鮮花的圖像數(shù)據(jù),包含 17 不同種類的鮮花,每類 80 張該類鮮花的圖片,鮮花種類是英國地區(qū)常見鮮花。下載數(shù)據(jù)后解壓文件,然后將不同的花剪切到對應(yīng)的文件夾,如下圖所示:
每個文件夾下面有80個圖片文件。
二、使用的工具
首先是在tensorflow框架下,然后介紹一下用到的兩個庫,一個是os,一個是PIL。PIL(Python Imaging Library)是 Python 中最常用的圖像處理庫,而Image類又是 PIL庫中一個非常重要的類,通過這個類來創(chuàng)建實例可以有直接載入圖像文件,讀取處理過的圖像和通過抓取的方法得到的圖像這三種方法。
三、代碼實現(xiàn)
我們是通過TFRecords來創(chuàng)建數(shù)據(jù)集的,TFRecords其實是一種二進制文件,雖然它不如其他格式好理解,但是它能更好的利用內(nèi)存,更方便復制和移動,并且不需要單獨的標簽文件(label)。
1、制作TFRecords文件
import os import tensorflow as tf from PIL import Image # 注意Image,后面會用到 import matplotlib.pyplot as plt import numpy as np cwd = 'D:\PyCharm Community Edition 2017.2.3\Work\google_net\jpg\\' classes = {'daffodil', 'snowdrop', 'lilyvalley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritiuary', 'sunflower', 'daisy', 'coltsfoot', 'dandelion', 'cowslip', 'buttercup', 'windflower', 'pansy'} # 花為 設(shè)定 17 類 writer = tf.python_io.TFRecordWriter("flower_train.tfrecords") # 要生成的文件 for index, name in enumerate(classes): class_path = cwd + name + '\\' for img_name in os.listdir(class_path): img_path = class_path + img_name # 每一個圖片的地址 img = Image.open(img_path) img = img.resize((224, 224)) img_raw = img.tobytes() # 將圖片轉(zhuǎn)化為二進制格式 example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])) })) # example對象對label和image數(shù)據(jù)進行封裝 writer.write(example.SerializeToString()) # 序列化為字符串 writer.close()
首先將文件移動到對應(yīng)的路徑:
D:\PyCharm Community Edition 2017.2.3\Work\google_net\jpg
然后對每個文件下的圖片進行讀寫和相應(yīng)的大小驚醒改變,具體過程是使用tf.train.Example來定義我們要填入的數(shù)據(jù)格式,其中l(wèi)abel即為標簽,也就是最外層的文件夾名字,img_raw為易經(jīng)理二進制化的圖片。然后使用tf.python_io.TFRecordWriter來寫入。基本的,一個Example中包含F(xiàn)eatures,F(xiàn)eatures里包含F(xiàn)eature(這里沒s)的字典。最后,F(xiàn)eature里包含有一個 FloatList, 或者ByteList,或者Int64List。就這樣,我們把相關(guān)的信息都存到了一個文件中,所以前面才說不用單獨的label文件。而且讀取也很方便。
執(zhí)行完以上代碼就會出現(xiàn)如下圖所示的TF文件
2、讀取TFRECORD文件
制作完文件后,將該文件讀入到數(shù)據(jù)流中,具體代碼如下:
def read_and_decode(filename): # 讀入dog_train.tfrecords filename_queue = tf.train.string_input_producer([filename]) # 生成一個queue隊列 reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) # 返回文件名和文件 features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw': tf.FixedLenFeature([], tf.string), }) # 將image數(shù)據(jù)和label取出來 img = tf.decode_raw(features['img_raw'], tf.uint8) img = tf.reshape(img, [224, 224, 3]) # reshape為128*128的3通道圖片 img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 # 在流中拋出img張量 label = tf.cast(features['label'], tf.int32) # 在流中拋出label張量 return img, label
注意,feature的屬性“l(fā)abel”和“img_raw”名稱要和制作時統(tǒng)一 ,返回的img數(shù)據(jù)和label數(shù)據(jù)一一對應(yīng)。
3、顯示tfrecord格式的圖片
為了知道TF 文件的具體內(nèi)容,或者是怕圖片對應(yīng)的label出錯,可以將數(shù)據(jù)流以圖片的形式讀出來并保存以便查看,具體的代碼如下:
filename_queue = tf.train.string_input_producer(["flower_train.tfrecords"]) # 讀入流中 reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) # 返回文件名和文件 features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw': tf.FixedLenFeature([], tf.string), }) # 取出包含image和label的feature對象 image = tf.decode_raw(features['img_raw'], tf.uint8) image = tf.reshape(image, [224, 224, 3]) label = tf.cast(features['label'], tf.int32) label = tf.one_hot(label, 17, 1, 0) with tf.Session() as sess: # 開始一個會話 init_op = tf.initialize_all_variables() sess.run(init_op) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(100): example, l = sess.run([image, label]) # 在會話中取出image和label img = Image.fromarray(example, 'RGB') # 這里Image是之前提到的 img.save(cwd + str(i) + '_''Label_' + str(l) + '.jpg') # 存下圖片 print(example, l) coord.request_stop() coord.join(threads)
執(zhí)行以上代碼后,當前項目對應(yīng)的文件夾下會生成100張圖片,還有對應(yīng)的label,如下圖所示:
在這里我們可以看到,前80個圖片文件的label是1,后20個圖片的label是2。 由此可見,我們一開始制作tfrecord文件時,圖片分類正確。
完整代碼如下:
import os import tensorflow as tf from PIL import Image # 注意Image,后面會用到 import matplotlib.pyplot as plt import numpy as np cwd = 'D:\PyCharm Community Edition 2017.2.3\Work\google_net\jpg\\' classes = {'daffodil', 'snowdrop', 'lilyvalley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritiuary', 'sunflower', 'daisy', 'coltsfoot', 'dandelion', 'cowslip', 'buttercup', 'windflower', 'pansy'} # 花為 設(shè)定 17 類 writer = tf.python_io.TFRecordWriter("flower_train.tfrecords") # 要生成的文件 for index, name in enumerate(classes): class_path = cwd + name + '\\' for img_name in os.listdir(class_path): img_path = class_path + img_name # 每一個圖片的地址 img = Image.open(img_path) img = img.resize((224, 224)) img_raw = img.tobytes() # 將圖片轉(zhuǎn)化為二進制格式 example = tf.train.Example(features=tf.train.Features(feature={ "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])), 'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])) })) # example對象對label和image數(shù)據(jù)進行封裝 writer.write(example.SerializeToString()) # 序列化為字符串 writer.close() def read_and_decode(filename): # 讀入dog_train.tfrecords filename_queue = tf.train.string_input_producer([filename]) # 生成一個queue隊列 reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) # 返回文件名和文件 features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw': tf.FixedLenFeature([], tf.string), }) # 將image數(shù)據(jù)和label取出來 img = tf.decode_raw(features['img_raw'], tf.uint8) img = tf.reshape(img, [224, 224, 3]) # reshape為128*128的3通道圖片 img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 # 在流中拋出img張量 label = tf.cast(features['label'], tf.int32) # 在流中拋出label張量 return img, label filename_queue = tf.train.string_input_producer(["flower_train.tfrecords"]) # 讀入流中 reader = tf.TFRecordReader() _, serialized_example = reader.read(filename_queue) # 返回文件名和文件 features = tf.parse_single_example(serialized_example, features={ 'label': tf.FixedLenFeature([], tf.int64), 'img_raw': tf.FixedLenFeature([], tf.string), }) # 取出包含image和label的feature對象 image = tf.decode_raw(features['img_raw'], tf.uint8) image = tf.reshape(image, [224, 224, 3]) label = tf.cast(features['label'], tf.int32) label = tf.one_hot(label, 17, 1, 0) with tf.Session() as sess: # 開始一個會話 init_op = tf.initialize_all_variables() sess.run(init_op) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(100): example, l = sess.run([image, label]) # 在會話中取出image和label img = Image.fromarray(example, 'RGB') # 這里Image是之前提到的 img.save(cwd + str(i) + '_''Label_' + str(l) + '.jpg') # 存下圖片 print(example, l) coord.request_stop() coord.join(threads)
本人也是剛剛學習深度學習,能力有限,不足之處請見諒,歡迎大牛一起討論,共同進步!
以上這篇對python制作自己的數(shù)據(jù)集實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- python merge、concat合并數(shù)據(jù)集的實例講解
- python 實現(xiàn)對數(shù)據(jù)集的歸一化的方法(0-1之間)
- python:pandas合并csv文件的方法(圖書數(shù)據(jù)集成)
- python 劃分數(shù)據(jù)集為訓練集和測試集的方法
- Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法
- 對python中數(shù)據(jù)集劃分函數(shù)StratifiedShuffleSplit的使用詳解
- Python數(shù)據(jù)集切分實例
- Python讀取數(shù)據(jù)集并消除數(shù)據(jù)中的空行方法
- python 篩選數(shù)據(jù)集中列中value長度大于20的數(shù)據(jù)集方法
- python調(diào)用攝像頭拍攝數(shù)據(jù)集
相關(guān)文章
python scipy.spatial.distance 距離計算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計算函數(shù),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03【Python】Python的urllib模塊、urllib2模塊批量進行網(wǎng)頁下載文件
這篇文章主要介紹了Python的urllib模塊、urllib2模塊批量進行網(wǎng)頁下載文件,就是一個簡單的從網(wǎng)頁抓取數(shù)據(jù)、下載文件的小程序,需要的可以了解一下。2016-11-11淺談TensorFlow中讀取圖像數(shù)據(jù)的三種方式
這篇文章主要介紹了淺談TensorFlow中讀取圖像數(shù)據(jù)的三種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06Python使用ThreadPoolExecutor一次開啟多個線程
通過使用ThreadPoolExecutor,您可以同時開啟多個線程,從而提高程序的并發(fā)性能,本文就來介紹一下Python使用ThreadPoolExecutor一次開啟多個線程,感興趣的可以了解一下2023-11-11Python?計算機視覺編程進階之OpenCV?圖像銳化及邊緣檢測
計算機視覺這種技術(shù)可以將靜止圖像或視頻數(shù)據(jù)轉(zhuǎn)換為一種決策或新的表示。所有這樣的轉(zhuǎn)換都是為了完成某種特定的目的而進行的,本篇我們來學習下如何對圖像進行銳化處理以及如何進行邊緣檢測2021-11-11Python實現(xiàn)學生管理系統(tǒng)的完整代碼(面向?qū)ο?
這篇文章主要介紹了Python實現(xiàn)學生管理系統(tǒng)的完整代碼(面向?qū)ο?,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04Python代碼中引用已經(jīng)寫好的模塊、方法的兩種方式
這篇文章主要介紹了Python代碼中引用已經(jīng)寫好的模塊、方法,下面就介紹兩種方式,可以簡潔明了地調(diào)用自己在其他模塊寫的代碼,需要的朋友可以參考下2022-07-07