我使用tensorflow_hub模块执行神经风格转换,得到错误“图像”不包含形状”。我不明白我在哪里犯了错误
这是我的代码:
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
content_path = r'C:\Users\Sriram\Desktop\efil.jpg'
style_path = r'C:\Users\Sriram\Desktop\download1.jfif'
content_image = plt.imread(content_path)
style_image = plt.imread(style_path)
plt.subplot(1, 2, 1)
plt.title('Content Image')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.title('Style Image')
plt.axis('off')
def image_to_tensor(path_to_img):
img = tf.io.read_file(path_to_img)
img = tf.image.decode_image(img, channels=3, dtype=tf.float32)
# Resize the image to specific dimensions
img = tf.image.resize(img, [720, 512])
img = img[tf.newaxis, :]
return img
def tensor_to_image(tensor):
tensor = tensor*255
tensor = np.array(tensor, dtype=np.uint8)
tensor = tensor[0]
plt.figure(figsize=(20,10))
plt.axis('off')
return plt.imshow(tensor)
content_image_tensor = image_to_tensor(content_path)
style_image_tensor = image_to_tensor(style_path)
hub_module = hub.load('https://tfhub.dev/google/magenta/arbitrary-image-stylization-v1-256/2')
combined_result = hub_module(tf.constant(content_image_tensor), tf.constant(style_image_tensor))[0]
result=tensor_to_image(combined_result)
以下是错误:
runfile('C:/Users/Sriram/.spyder-py3/temp.py', wdir='C:/Users/Sriram/.spyder-py3')
Traceback (most recent call last):
File "C:\Users\Sriram\.spyder-py3\temp.py", line 30, in <module>
content_image_tensor = image_to_tensor(content_path)
File "C:\Users\Sriram\.spyder-py3\temp.py", line 20, in image_to_tensor
img = tf.image.resize(img, [720, 512])
File "C:\Users\Sriram\anaconda3\lib\site-packages\tensorflow\python\ops\image_ops_impl.py", line 1182, in resize_images
skip_resize_if_same=True)
File "C:\Users\Sriram\anaconda3\lib\site-packages\tensorflow\python\ops\image_ops_impl.py", line 1029, in _resize_images_common
raise ValueError('\'images\' contains no shape.')
ValueError: 'images' contains no shape
您的代码在TensorFlow 2.2上运行良好,因此我假设您在TensorFlow 1.x上使用
decode_image
击中了somewhat known issue:当“一般”解码图像时,形状不会返回-这使得对resize()
的调用失败。有多种方法可以做到这一点利用已知的图像大小
如果您事先知道图像的大小,可以使用^{} 方法(并然后调整大小)将大小强制到张量上:
利用已知的图像格式
如果您知道所有图像都是JPEG格式的,那么可以使用
decode_jpeg
来代替,这会更好一些:使用带裁剪和填充的“调整大小”
或者,您可以尝试使用tf.image.resize_with_crop_or_pad,这显然可以解决该问题:
不过有一个警告:代码假定所有操作都是急切地执行的,这是TensorFlow 2.x上的默认值,而不是TensorFlow 1.x上的默认值。因此,
tensor_to_image(tensor)
函数将失败,因为提供的张量不能简单地转换为NumPy数组。要解决此问题,可以在脚本开始时运行enable eager execution另一方面,您可以使用^{} 和^{} 将图像转换回:
这将确保所有值都正确饱和(例如,在转换为
np.float32
时,0..1
之外不会有值),并摆脱一些神奇的[0]
索引相关问题 更多 >
编程相关推荐