將SynthText數(shù)據(jù)轉(zhuǎn)成tfrecord

主要涉及兩方面:

  1. mat文件的讀取
  2. 構(gòu)建自己的tfrecord數(shù)據(jù)集

python讀取.mat文件

import scipy.io as sio
mat = sio.loadmat(matdir)

SynthText數(shù)據(jù)集

這一節(jié)講gt.mat中的數(shù)據(jù)揭朝,可略過不讀
下載地址:http://www.robots.ox.ac.uk/~vgg/data/scenetext/
包含858,750張圖片
gt.mat中包含imnames,txt,globals,charBB,hearder,version,wordBB等
其中:
mat['imnames'][0] 放圖片相對地址
mat['wordBB'][0] 放bbox的位置信息诬留,張量的維度是24圖片中包含的word數(shù)量,實際操作中一定要小心超出它的值圖片大小范圍
mat['txt'][0] 放每張圖片中包含的文本字符串杯矩。注意,它將在相同區(qū)域呈現(xiàn)相同字體,顏色币砂,變形等的組合在一起;因此可能與wordBB中對應(yīng)圖片中word數(shù)量不一致。
比如:

>>mat['imnames'][0][0]
array(['8/ballet_106_0.jpg'],
      dtype='<U18')

對應(yīng)下圖


ballet_106_0.jpg
>>mat['txt'][0][0]
array(['Lines:\nI lost\nKevin ', 'will                ',
       'line\nand            ', 'and\nthe             ',
       '(and                ', 'the\nout             ',
       'you                 ', "don't\n pkg          "],
      dtype='<U20')
>>mat['wordBB'][0][0].shape
(2,4,15)

因此我們對mat['txt']中的數(shù)據(jù)要經(jīng)過strip()去掉空格琉挖,re.split()分割后在進行轉(zhuǎn)tfrecord操作,以對mat['txt'][0][0]的處理為例

for val in mat['txt'][0][0]:
     v = [x.encode('ascii') for x in re.split("[ \n]", val.strip()) if x]
     str.extend(v)

代碼

import numpy as np
import scipy.io as sio
import os
import re
import Image
import tensorflow as tf
import sys

def arr2list(x):
     ""'confirm every member is in [0.0,1.0]
        convert np.array to a list
    """
    x[x>1] = 1
    x[x<0] = 0
    return list(x)

def int64_feature(value):
    """Wrapper for inserting int64 features into Example proto.
    """
    if not isinstance(value, list):
        value = [value]
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))


def float_feature(value):
    """Wrapper for inserting float features into Example proto.
    """
    if not isinstance(value, list):
        value = [value]
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))


def bytes_feature(value):
    """Wrapper for inserting bytes features into Example proto.
    """
    if not isinstance(value, list):
        value = [value]
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))


def _convert_to_example(image_name, labels, labels_text, bboxes, shape,
                        difficult=0, truncated=0):
    """Build an Example proto for an image example.

    Args:
      image_data: string, JPEG encoding of RGB image;
      labels: list of integers, identifier for the ground truth;
      labels_text: list of text-string;
      bboxes: list of bounding boxes; each box is a list of integers;
          specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong
          to the same label as the image label.
      shape: 3 integers, image shapes in pixels.
    Returns:
      Example proto
    """
    image_data = tf.gfile.FastGFile(image_name, 'rb').read()
    xmin = bboxes[0]
    ymin = bboxes[1]
    xmax = bboxes[2]
    ymax = bboxes[3]
    image_format = b'JPEG'
    example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': int64_feature(shape[1]),
        'image/width': int64_feature(shape[0]),
        'image/channels': int64_feature(shape[2]),
        'image/shape': int64_feature(shape),
        'image/object/bbox/xmin': float_feature(xmin),
        'image/object/bbox/xmax': float_feature(xmax),
        'image/object/bbox/ymin': float_feature(ymin),
        'image/object/bbox/ymax': float_feature(ymax),
        'image/object/bbox/label': int64_feature(labels),
        'image/object/bbox/label_text': bytes_feature(labels_text),
        'image/object/bbox/difficult': int64_feature(difficult),
        'image/object/bbox/truncated': int64_feature(truncated),
        'image/format': bytes_feature(image_format),
        'image/encoded': bytes_feature(image_data)}))
    return example


mat_dir = 'gt.mat'
txt_dir = "info.txt"

# get gt.mat
mat = sio.loadmat(mat_dir)
print('load gt.mat')
input("continue")

# get imformation
imnames = mat['imnames'][0]
txt = mat['txt'][0]
wordBB = mat['wordBB'][0]

# set TFrecord dir set
tf_dir_set = set()
tf_writer = None
tf_dirs = "ttfrecords"

total_count = 0


i = 0
need = set()
while i < imnames.size:
    try:
        image_dir = imnames[i][0]
        tfrecord_name = os.path.split(image_dir)[0]
    
        if not tfrecord_name in tf_dir_set:
            # 新開一個tfwriter
            if tf_writer is not None:
                tf_writer.close()
            tf_name = ("%s/synthText_%s.tfrecords" % (tf_dirs, tfrecord_name))
            tf_writer = tf.python_io.TFRecordWriter(tf_name)
            tf_dir_set.add(tfrecord_name)

        img_size = Image.open(image_dir).size
        shape = [img_size[0], img_size[1], 3]
        if len(wordBB[i][0].shape) >1:
            minx = np.amin(wordBB[i][0], axis=0) / img_size[0]
            miny = np.amin(wordBB[i][1], axis=0) / img_size[1]
            maxx = np.amax(wordBB[i][0], axis=0) / img_size[0]
            maxy = np.amax(wordBB[i][1], axis=0) / img_size[1]
        else:
            minx = [np.amin(wordBB[i][0]) / img_size[0]]
            miny = [np.amin(wordBB[i][1]) / img_size[1]]
            maxx = [np.amax(wordBB[i][0]) / img_size[0]]
            maxy = [np.amax(wordBB[i][1]) / img_size[1]]
        #檢查是否有>1的情況启泣,并轉(zhuǎn)為list
        minx = arr2list(minx)
        miny = arr2list(miny)
        maxy = arr2list(maxy)
        maxx = arr2list(maxx)
        bboxes = [minx, miny, maxx, maxy]

        str = []
        for val in txt[i]:
            v = [x.encode('ascii') for x in re.split("[ \n]", val.strip()) if x]
            str.extend(v)

        labels = [1] * len(str)

        example = _convert_to_example(image_dir, labels, str, bboxes, shape)
        tf_writer.write(example.SerializeToString())
        sys.stdout.write('\r>> Converting image %d/%d' % (i + 1, imnames.size))
        sys.stdout.flush()
        i = i + 1
        total_count += 1
    except Exception as e:
        print(e)
        choose = input("continue?Y/N")
        if choose == "Y":
            i = i+1
        else:
            sys.exit()
print("Converting image competely! totally %d records" % (total_count))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市示辈,隨后出現(xiàn)的幾起案子寥茫,更是在濱河造成了極大的恐慌,老刑警劉巖矾麻,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件纱耻,死亡現(xiàn)場離奇詭異,居然都是意外死亡险耀,警方通過查閱死者的電腦和手機弄喘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來甩牺,“玉大人蘑志,你說我怎么就攤上這事”崤桑” “怎么了急但?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長搞乏。 經(jīng)常有香客問我波桩,道長,這世上最難降的妖魔是什么查描? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任突委,我火速辦了婚禮,結(jié)果婚禮上冬三,老公的妹妹穿的比我還像新娘匀油。我一直安慰自己,他們只是感情好勾笆,可當我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布敌蚜。 她就那樣靜靜地躺著,像睡著了一般窝爪。 火紅的嫁衣襯著肌膚如雪弛车。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天蒲每,我揣著相機與錄音纷跛,去河邊找鬼。 笑死邀杏,一個胖子當著我的面吹牛贫奠,可吹牛的內(nèi)容都是我干的唬血。 我是一名探鬼主播,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼唤崭,長吁一口氣:“原來是場噩夢啊……” “哼拷恨!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起谢肾,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤腕侄,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后芦疏,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體冕杠,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年眯分,在試婚紗的時候發(fā)現(xiàn)自己被綠了拌汇。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡弊决,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出魁淳,到底是詐尸還是另有隱情飘诗,我是刑警寧澤,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布界逛,位于F島的核電站昆稿,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏息拜。R本人自食惡果不足惜溉潭,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望少欺。 院中可真熱鬧喳瓣,春花似錦、人聲如沸赞别。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽仿滔。三九已至惠毁,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間崎页,已是汗流浹背鞠绰。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留飒焦,地道東北人蜈膨。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親丈挟。 傳聞我的和親對象是個殘疾皇子刁卜,可洞房花燭夜當晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容