我想使用TensorFlow 2数据集对象向CNN提供图像。我的图片位于AWSS3上,但我将在我的示例中使用来自Wikipedia的图片(问题是相同的)
image_urls = [
'https://upload.wikimedia.org/wikipedia/commons/6/60/Matterhorn_from_Domh%C3%BCtte_-_2.jpg',
'https://upload.wikimedia.org/wikipedia/commons/6/6e/Matterhorn_from_Klein_Matterhorn.jpg',
]
dataset = tf.data.Dataset.from_tensor_slices(image_urls)
def read_image_from_url(url):
img_array = None
with urlopen(url) as request:
img_array = np.asarray(bytearray(request.read()), dtype=np.uint8)
img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #as RGB image (cv2 is BGR by default)
当我使用数据集的一个元素测试我的函数时,它可以工作:
url = next(iter(dataset)).numpy().decode('utf-8')
img = read_image_from_url(url)
plt.imshow(img)
但是,当我将函数映射到数据集以创建为图像服务的新数据集时,它失败了:
dataset_images = dataset.map(lambda x: read_image_from_url(x.numpy().decode('utf-8')))
AttributeError: in converted code:
<ipython-input-6-e8eb89833196>:2 None *
map_func=lambda x: read_image_from_url(x.numpy().decode('utf-8')),
AttributeError: 'Tensor' object has no attribute 'numpy'
显然,当使用next
或map
进行迭代时,数据集提供了不同的数据类型。你知道我该怎么解决这个问题吗
这比实际情况要困难得多:
为什么第一个可以工作,但在
tf.Dataset
中失败了?那么tf.Dataset
是在graph mode
中定义的,而不是像第一个一样在eager mode
中定义的。图形模式更快,而且tf.Dataset
针对速度进行了优化,因此它是有意义的。您不能在图形模式下执行.numpy()
,因为所有内容都应该在tensorflow
操作中定义py_func
将python函数包装在tf.Operation
中,该函数在eager mode
中执行,这正是我们所需要的注意:我尝试了
tf.keras.utils.get_file()
,但遇到了与您在这里描述的类似的问题。希望这有帮助相关问题 更多 >
编程相关推荐