1 介紹
本文将mxNet的資料格式轉化為tensorflow訓練用的資料格式。
2 導入包
import mxnet as mx
import argparse
import PIL.Image
import io
import numpy as np
import cv2
import tensorflow as tf
import os
3 主函數
if __name__ == '__main__': # define parameters id2range = {} data_shape = (3, 112, 112) args = parse_args() #idx_path放的是索引;args.bin_path放的是值,讀取的話imgrec是一個IO的對象,可以了解為C++裡面的類對象,類對象裡面有很多成員; # 比如有成員代表索引,成員代表索引對應的值得等。keys的len代表索引的數量 imgrec = mx.recordio.MXIndexedRecordIO(args.idx_path, args.bin_path, 'r')#索引長度5898396,也就是idx的長度 s = imgrec.read_idx(0)#讀取最開始那個索引對應的key_value,不過s是二進制形式的 header, _ = mx.recordio.unpack(s)#header這裡存儲的是分成2斷的索引(key),這個時候不關心對應的資料資料,key是(5822653,5898396)的這一對索引 #(0,5822653)(5822653,5898396)這樣把資料分成兩段 print(header.label)#header.label就是(5822653,5898396) #下面是分成兩段 imgidx = list(range(1, int(header.label[0]))) seq_identity = range(int(header.label[0]), int(header.label[1])) for identity in seq_identity:#處理後面那段資料 s = imgrec.read_idx(identity) header, _ = mx.recordio.unpack(s) a, b = int(header.label[0]), int(header.label[1]) id2range[identity] = (a, b)#代表的是id為identity的起始索引從a到b,[a,b) print('id2range', len(id2range)) # # generate tfrecords mx2tfrecords(imgidx, imgrec, args) |
4 轉化函數
def mx2tfrecords(imgidx, imgrec, args):#從(0,5822653)的圖檔 output_path = os.path.join(args.tfrecords_file_path, 'tran.tfrecords') writer = tf.python_io.TFRecordWriter(output_path) for i in imgidx: img_info = imgrec.read_idx(i)#取出第i張圖檔,包括索引和圖檔資料 header, img = mx.recordio.unpack(img_info)#解封 label = int(header.label)#取出這張圖檔的标簽 example = tf.train.Example(features=tf.train.Features(feature={ 'image_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img])), "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label])) }))#把這張圖檔的标簽和圖檔資料都存下來 writer.write(example.SerializeToString()) # Serialize To String if i % 10000 == 0: print('%d num image processed' % i) writer.close() |
5 關于資料
本文例子中用到的資料可以私聊我要,畢竟是需要時間成本的,随便發個紅包大小随意。
歡迎大家關注和轉發本公衆号:facefinetune
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiInBnaugTO1ADNzMTMyATNwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)