Introduction
Tensor Flowで畳み込みたい
だけど画像のサイズを整形するのが面倒っていうことがよくありました
自分はこれまではSonyのを使いバラバラな縦横比を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_width
とnew_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