gorogoroyasu

福岡の開発会社で働いている。

tensorflowのrandom crop で、2枚の画像の同じ箇所を切り取る

画像が2枚あります。
画像A が入力データ 画像B が正解データ。

f:id:adiboy:20181026102449p:plain 画像引用: https://helpx.adobe.com/jp/photoshop-elements/kb/222341.html

この画像をrandom crop するときに、どのようにするとうまくcrop できるのか試しました。
そして、たどり着いた答えが以下のコード。
もっといい方法があるのかもですが、とりあえずこれで動きます。

import tensorflow as tf
import numpy as np
import random

# この二つの配列を、画像と見立てる
img1 = np.arange(300).reshape((10, 10, 3))
img2 = np.arange(300).reshape((10, 10, 3)) + 300

i1 = tf.constant(img1)
i2 = tf.constant(img2)

with tf.Session() as s:
    s.run(tf.global_variables_initializer())
    seed = random.randint(0, 1000)
    croped_img1 = tf.random_crop(i1, [5, 5, 3], seed=seed)
    croped_img2 = tf.random_crop(i2, [5, 5, 3], seed=seed)
    c1 = s.run(croped_img1)
    c2 = s.run(croped_img2)    
"""
c2 - c1 => array([[[300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300]],

       [[300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300]],

       [[300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300]],

       [[300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300]],

       [[300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300],
        [300, 300, 300]]])
"""

おそらくこれで切れているんだと思います。 ということで、random_crop に seed を入れてあげれば解決。 以上。

追記。

俺のやりたかったことは、そんなんじゃない!!!! こんな記事、嘘っぱちだ。

dataset API の中で、どうやってそれ使えばいいんだ(怒)

ということで、調べた。

import tensorflow as tf
import numpy as np
import random

# 画像 (10枚)
img1 = np.arange(3000).reshape((-1, 10, 10, 3))
img2 = np.arange(3000).reshape((-1, 10, 10, 3)) + 300

def _parse_function(img1, img2):
    r = tf.get_seed(1)
    img1 = tf.random_crop(img1, [5, 5, 3], seed=r[0])
    img2 = tf.random_crop(img2, [5, 5, 3], seed=r[0])
    return img1, img2

dataset = tf.data.Dataset.from_tensor_slices((i1, i2))
dataset = dataset.map(_parse_function, num_parallel_calls=2)
dataset = dataset.shuffle(buffer_size=(len(img1))).batch(1).prefetch(1).repeat()
iterator = dataset.make_one_shot_iterator().get_next()

with tf.Session() as sess:
    for i in range(5):
        x, y = sess.run(iterator)
        print(x[0, 0, 0])
print(y - x)

結果

[2823 2824 2825]
[675 676 677]
[1932 1933 1934]
[2232 2233 2234]
[2436 2437 2438]
[[[[300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]]

  [[300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]]

  [[300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]]

  [[300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]]

  [[300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]
   [300 300 300]]]]

ということで、ランダムに画像を crop しつつ、対象の2枚の画像については同じ箇所で切り出すことができた。