title: Tensorflow: How to randomly crop input images and labels in the same way?
body: <p>I'm trying to take random crops from an image. Just like it's done in Caffe for the sake of data augmentation.</p>
  
  <p>I know that tensorflow already has a function</p>
  
  <pre><code>    img = tf.random_crop(img, [h, w, 3])
      label = tf.random_crop(label, [h, w, 1])
  </code></pre>
  
  <p>But I'm not sure whether it takes it takes the same crop for image and label. Also this function cannot automatically 0-pad images with one or two dimensions smaller than the crop size [h,w].</p>
  
  <p>That again is done by</p>
  
  <pre><code>    img = tf.image.resize_image_with_crop_or_pad(img, h, w)
      label = tf.image.resize_image_with_crop_or_pad(label, h, w)
  </code></pre>
  
  <p>But it takes only center crops not random crops.</p>
  
  <p>Edit:<br>
  Here is some code how the padding could be done: </p>
  
  <pre><code># Cropping dimensions (crops of 700 x 800)
  crp_h = tf.constant(700)
  crp_w = tf.constant(800)
  
  shape = tf.shape(img)
  img_h = shape[0]
  img_w = shape[1]    
  img = tf.cond(img_h &lt; crp_h, lambda: tf.image.pad_to_bounding_box(img, 0, 0, crp_h, img_w), lambda: img)
  # Update image dimensions
  shape = tf.shape(img)
  img_h = shape[0]
  img = tf.cond(img_w &lt; crp_w, lambda: tf.image.pad_to_bounding_box(img, 0, 0, img_h, crp_w), lambda: img)
  # Update image dimensions
  shape = tf.shape(img)
  img_w = shape[1]
  </code></pre>
  
  <p>Unfortunately one cannot use the python <code>if</code> conditional here so one has to go with the ugly <code>tf.cond(...)</code> instead.</p>