11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

tf.image.decode_jpegからTensorFlow

Last updated at Posted at 2016-05-07

あれやこれやとチュートリアルを見ながら四苦八苦、

こちらを参考にさせて頂いて、画像さえ用意すれば動かせるところまで行きました。
でもOpenCVの利用が前提なんですよね。

目標としてはAWS Lambdaの上で動かしたかったので、こうなると

に従う必要があって、デプロイ用のマシンをいじる必要があり、ちょっと面倒です。
cv2で読み込むのと微妙に結果は違ってしまうんですが、tf.image.decode_jpegを使ったコードを書いてみました。

# !/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf

NUM_CLASSES = 2
IMAGE_SIZE = 28
TRAIN_SECTION = 2

flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('train', 'train/train.csv', 'File name of train data')

if __name__ == '__main__':
    raw_input = np.loadtxt(open(FLAGS.train), delimiter=",", dtype=str)
    [trains, tests] = np.vsplit(raw_input, [TRAIN_SECTION])

    with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        train_image, train_label = get_image_and_label(sess, trains)
        test_image, test_label = get_image_and_label(sess, tests)

def get_image_and_label(sess, csv_lines):
    images = []
    labels = []
    for train in csv_lines:
        val = tf.cast(train[0], dtype=tf.string)
        jpeg_r = tf.read_file(val)
        image = tf.image.decode_jpeg(jpeg_r, channels=3)
        image = tf.image.resize_images(image, IMAGE_SIZE, IMAGE_SIZE)
        image = tf.reshape(image, [-1])
        image_val = sess.run(image).astype(np.float32) / 255.0
        images.append(image_val)
        tmp = np.zeros(NUM_CLASSES)
        tmp[int(train[1])] = 1
        labels.append(tmp)

    return np.asarray(images, dtype=np.float32), np.asarray(labels, dtype=np.float32)

train.csvの中身は

train/1.jpg,0
train/2.jpg,1
train/3.jpg,1

みたいな感じです。上記のコードでは2行目までを学習用、残りを試験用としています。

よし、次はAWS Lambdaへのデプロイと画像データの準備だ!
(そしてCNNの基礎とか勉強しなきゃ、、)

11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?