在做TensorFlow案例時好多圖片數據集都是可以直接在庫中調用的,比如Mnist,CIFAR-10等等。但是在跑自己項目的時候如何去讀取自己的數據集呢?這裏有兩種方法制作數據集。1.CSV文件的讀取
2.TFRecords文件的讀取。
1.CSV文件的創建與讀取
新建名爲jpg的文件夾,其中有若干圖片是需要對其讀取地址和標籤的對象。path作爲文件夾的路徑被設定,之後的filename是讀取文件路徑。通過調用文件夾內容的遞歸查詢,重新以需要的格式拼接字符串並重新寫入。csv文件每一行被逗號分成兩部分,前一部分是圖片的地址,後一部分是設定的標籤名。
import os
path = r'C:\Users\Qiuyi\...\datasets\jpg_splitCodes'
filenames=os.listdir(path)
strText = ""
with open("train_list.csv", "w") as fid:
for a in range(len(filenames)):
strText = path+os.sep+'code' + filenames[a] + "," + filenames[a].split('.')[0] + "\n"
fid.write(strText)
fid.close()
讀取數據時需要2個數組分別存放讀取的圖片地址和標籤,對於CSV文件調用readlines函數即可。
tf.read_line(image_path):讀取圖片地址的函數(tensorflow中地址信息也需要用函數讀取)
tf.image.decode_jpeg:對讀取進來的圖片解碼成JPG格式,並在此設定了圖像的通道。channels=1表示讀取的圖像爲灰度。
tf.image.convert_image_dtype:對圖像進行轉化,將圖像矩陣轉化成tensorflow需要的張量格式。
import tensorflow as tf
import cv2
image_add_list = []
image_label_list = []
with open("train_list.csv") as fid:
for image in fid.readlines():
image_add_list.append(image.strip().split(",")[0])
image_label_list.append(image.strip().split(",")[1])
def get_image(image_path):
return tf.image.convert_image_dtype(
tf.image.decode_jpeg(
tf.read_file(image_path), channels=1),
dtype=tf.uint8)
img = tf.image.convert_image_dtype(tf.image.decode_jpeg(tf.read_file('3.jpeg'), channels=1),dtype=tf.uint8)
with tf.Session() as sess:
cv2Img = sess.run(img)
img2 = cv2.resize(cv2Img, (200,200))
cv2.imshow('image', img2)
cv2.waitKey()