tf.image.resize_images() expects statically known rank
It looks like the op tf.image.resize_images() has no effect on the image shape when the parameters new_height and new_width are dynamically computed (this is possible since the fix of issue #1001).
For example, this piece of code
shape = tf.shape(image)
height = shape[0]
width = shape[1]
new_shorter_edge = tf.constant(400, dtype=tf.int32)
height_smaller_than_width = tf.less_equal(height, width)
new_height_and_width = tf.cond(
height_smaller_than_width,
lambda: (new_shorter_edge, _compute_longer_edge(height, width, new_shorter_edge)),
lambda: (_compute_longer_edge(width, height, new_shorter_edge), new_shorter_edge)
)
image = tf.image.resize_images(image, new_height_and_width[0], new_height_and_width[1])
image = tf.Print(image, [tf.shape(image), height, width, new_height_and_width[0], new_height_and_width[1]])
return tf.image.random_crop(image, [224, 224])
throws the following exception:
I tensorflow/core/kernels/logging_ops.cc:79] [122 160 3][122][160][400][524]
W tensorflow/core/common_runtime/executor.cc:1096] 0x7f9c08008490 Compute status: Failed precondition: width must be >= target_width: width = 160, target_width = 224
So as you can see in the first line of the printout, the shape of the image is not affected by tf.image.resize_images. Is this a bug or am I doing something wrong?
I also made up a workaround for this:
image = tf.expand_dims(image, 0)
image = tf.image.resize_bilinear(image, tf.pack(new_height_and_width))
image = tf.squeeze(image, [0])
image = tf.Print(image, [tf.shape(image), height, width, new_height_and_width[0], new_height_and_width[1]])
return tf.image.random_crop(image, [224, 224])
for example prints
I tensorflow/core/kernels/logging_ops.cc:79] [400 711 3][281][500][400][711]
@shlens: Do you know the correct way to fix this?
resize_images is light wrapper around several resizing kernels, including resize_bilinear, resize_bicubic, etc. The light wrapper functionality is intended to "assist" with the shape information and 3d and 4d images seemlessly. If you do not need all of these "assists" for shape information and 3d/4d images, could you call the underlying functions directly, e.g. resize_bilinear?
I renamed the issue. Ideally resize_image wouldn't require shapes to be known statically; certainly there's nothing fundamental about the underlying ops that requires it.
I'll work on this
@fayeshine: Thank you! Let me know if you have questions.
@girving , tf.image.random_crop has changed to tf.random_crop. And now this bug seems to be solved naturally. I can use resize_images to correctly resize images using the following codes.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
import matplotlib.pyplot as plt
arr = mnist.train.images[:10].reshape([10,28,28,1])
plt.imshow(arr[5,:,:,0])
images = tf.convert_to_tensor(arr, name='images')
def _compute_longer_edge(height, width, new_shorter_edge):
return tf.cast(width*new_shorter_edge/height, tf.int32)
shape = tf.shape(images)
height = shape[1]
width = shape[2]
new_shorter_edge = tf.constant(400, dtype=tf.int32)
height_smaller_than_width = tf.less_equal(height, width)
new_height_and_width = tf.cond(
height_smaller_than_width,
lambda: (new_shorter_edge, _compute_longer_edge(height, width, new_shorter_edge)),
lambda: (_compute_longer_edge(width, height, new_shorter_edge), new_shorter_edge)
)
images_ = tf.image.resize_images(images, new_height_and_width[0], new_height_and_width[1])
#image = tf.image.resize_bilinear(images, tf.pack(new_height_and_width))
images_ = tf.Print(images_, [tf.shape(images_), height, width, new_height_and_width[0], new_height_and_width[1]])
res = sess.run(tf.random_crop(images_, [10,224, 224,1]))
plt.imshow(res[5,:,:,0])
Aside: When you paste code format it by indenting four spaces; otherwise the code's indentation will go away.
In the code you've shown the sizes are statically known since images comes from convert_to_tensor. To exhibit the bug you'll have to make a tf.placeholder with no shape so that shape inference doesn't kick in.
@girving I tried to use tf.placeholder with no shape, however I still cannot reproduce this bug.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
sess = tf.InteractiveSession()
import matplotlib.pyplot as plt
arr = mnist.train.images[:10].reshape([10,28,28,1])
plt.imshow(arr[5,:,:,0])
#images = tf.convert_to_tensor(arr, name='images')
images = tf.placeholder(tf.float32, shape=[None,None,None,None])
#%%
def _compute_longer_edge(height, width, new_shorter_edge):
return tf.cast(width*new_shorter_edge/height, tf.int32)
shape = tf.shape(images)
height = shape[1]
width = shape[2]
new_shorter_edge = tf.constant(400, dtype=tf.int32)
height_smaller_than_width = tf.less_equal(height, width)
new_height_and_width = tf.cond(
height_smaller_than_width,
lambda: (new_shorter_edge, _compute_longer_edge(height, width, new_shorter_edge)),
lambda: (_compute_longer_edge(width, height, new_shorter_edge), new_shorter_edge)
)
images_ = tf.image.resize_images(images, new_height_and_width[0], new_height_and_width[1])
#image = tf.image.resize_bilinear(images, tf.pack(new_height_and_width))
images_ = tf.Print(images_, [tf.shape(images_), height, width, new_height_and_width[0], new_height_and_width[1]])
res = tf.random_crop(images_, [10,224,224,1]).eval(feed_dict={images: arr})
plt.imshow(res[5,:,:,0])
#%%
arr2 = mnist.train.images[10:20].reshape([10,56,14,1])
res2 = tf.random_crop(images_, [10,224,224,1]).eval(feed_dict={images: arr2})
plt.imshow(res2[5,:,:,0])
Please reformat the code as I mentioned so that it's easier to read.
@girving , sorry, I've formatted it by indenting four spaces. I was previously thinking that you mean use 4 spaces to replace tab. :smile:
@fayeshine: So close! It looks like resize_images goes out of its way to break only if the rank of the input tensor is unknown. Try using shape=None in your placeholder instead of shape=[None, None, None, None] and you should see a problem. However, I'm not sure if this is the same problem that @mackcmillion was experiencing.
@girving Yes, you are right, in this case resize_bilinear can work but resize_images throw an exception ValueError: 'images' contains no shape. .
I checked the code and found:
if images.get_shape().ndims is None:
raise ValueError('\'images\' contains no shape.')
# TODO(shlens): Migrate this functionality to the underlying Op's.
This seems like it is planned to move the resize_images function to the native c++ code.
In python, we cannot dynamically know what's shape of images(4-D or 3-D), so we cannot know what to do next.
So in this case, does it mean the solution should be move this in low-layer C++ part so we can know the shape in runtime?
@fayeshine: Yep, the cleanest way is probably to make all the C++ resize ops accept any number of dimensions >= 3 and treat the initial dims-3 dimensions as batch. There are a lot of other ops that behave this way: mixing together the last few dimensions and broadcasting over the first few.
As noted in #2286, resize_image_with_crop_or_pad has the same problem. It should be fixed in the same way.
I saw that resize_image_with_crop_or_pad was fixed, does this apply to the other cropping image ops or only this one? For instance crop_to_bouding_box.
It applies to anything that calls _Check3DImage with require_static=True (the default). The require_static option should go away entirely. Looks like crop_to_bounding_box uses require_static=False, so it's clean.
Are there any functions for Nearest neighbour upsampling of 3D images in tensorflow? Any workaround for this?
Automatically closing due to lack of recent activity. Since this issue is old at this point, please reopen the issue if it still occurs when tried with the latest version of Tensorflow. Thank you.
I think this is still a problem that should be addressed. Is a simple operation and it could be useful if you don't want to depend on other image libraries to do simple image transformations. Here is an example that shows the problem:
import tensorflow as tf
encoded_image_data = tf.placeholder(dtype=tf.string)
decoded_image = tf.image.decode_image(encoded_image_data, channels=3)
resized_image = tf.image.resize_images(decode_image, (800, 600))
encoded_image = tf.image.encode_jpeg(resized_image)
import urllib2
fd = urllib2.urlopen('https://c8.staticflickr.com/6/5753/20965045223_b809050285_o.jpg')
data = fd.read()
with tf.Session() as sess:
sess.run([encoded_image], { encoded_image_data: data})
output:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-41-bbd519ee1c20> in <module>()
4 encoded_image_data = tf.placeholder(dtype=tf.string)
5 decoded_image = tf.image.decode_image(encoded_image_data, channels=3)
----> 6 resized_image = tf.image.resize_images(decode_image, (800, 600))
7 encoded_image = tf.image.encode_jpeg(resized_image)
8
/home/fmilo/anaconda2/envs/tensorflow_built/lib/python2.7/site-packages/tensorflow/python/ops/image_ops_impl.pyc in resize_images(images, size, method, align_corners)
730 images = ops.convert_to_tensor(images, name='images')
731 if images.get_shape().ndims is None:
--> 732 raise ValueError('\'images\' contains no shape.')
733 # TODO(shlens): Migrate this functionality to the underlying Op's.
734 is_batch = True
ValueError: 'images' contains no shape.
For anyone else who runs into this problem, using the example above with the assumption of 3 Dims:
decoded_image = tf.image.decode_image(encoded_image_data, channels=3)
decoded_image.set_shape([None, None, None])
resized_image = tf.image.resize_images(decode_image, (800, 600))
This allows ndims to be returned (i.e. not be None) whilst allowing flexibility of resizing differently sized images.