LoginSignup
1
2

More than 5 years have passed since last update.

TensorFlowで画像整形

Posted at

Introduction

Tensor Flowで畳み込みたい
だけど画像のサイズを整形するのが面倒っていうことがよくありました

自分はこれまではSonyのNeural Network Consoleを使いバラバラな縦横比をPaddingさせて,縮小させるということをしていました
これもこれで良かったのですが不都合もあったのでこちらの記事を参考にTensor Flowで画像を整形しました

Requirements

  • TensoFlow (1.5.0以上)

Tensor Flow のEager Excursionを使いました
サイズが整っていないTensorを扱うのは面倒が多そうでしたので…
pip install tf-nightlyまたはpip install tf-nightly-gpuで使えるようになります
nightly buildで動作が不安定なので仮想環境での利用をおすすめします
自分はTensor Boardが動かなくなりました

Code

実行ファイルと同じディレクトリに置かれているoriginalフォルダ以下に変換したい画像を配置
copyファイル以下に整形した画像を置いていきます
new_widthnew_heightをいじれば縦横比は自在です

import tensorflow as tf

def reshape(image):
    """
    Making gotten images regular size.
    Arg:
        image: 3-D Tensor

    Return:
        reshaped: reshaped images
    """
    max_size = size_decision(image)
    new_height = 640
    new_width = 640

    reshaped = tf.image.resize_images(tf.image.resize_image_with_crop_or_pad(image, max_size, max_size),[new_height, new_width])
    return reshaped

def size_decision(image):
    """
    Helper function.
    Returning longer edge size.

    Arg:
        image: 3-D Tensor
    Return:
        size: longer edge size
    """
    return tf.reduce_max(tf.shape(image))

Run

自分のやり方だと実行部ではtfe.enableeager_execution()する必要がありました
形の違うNumpy配列を簡単にTensorに変換することは難しかったので,逐次処理しています
バッチ処理したほうがかっこいいと思うので,良い方法があれば教えてください…!
以下で多分動きます

if __name__=='__main__':
    import os
    import cv2
    import numpy as np
    import tensorflow.contrib.eager as tfe  # Version 1.5.0 or higher
    tfe.enable_eager_execution()
    DIRECTORY = './copy'

    image_names = [x for x in os.listdir('original')]

    for x in image_names:
        img = reshape(tf.constant(np.asarray(cv2.imread('original/'+x)))).numpy()
        print(cv2.imwrite(DIRECTORY+'/'+x, img))  # show T or F

1
2
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
1
2