I want to use a TensorFlow 2 dataset object to feed images to a CNN. My images are located on AWS S3, but I will use images from Wikipedia in my example (the problem is the same).
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)
When I test my function with one element of the dataset, it works:
url = next(iter(dataset)).numpy().decode('utf-8')
img = read_image_from_url(url)
plt.imshow(img)
But when I map my function to the dataset to create a new dataset serving the images, it fails:
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'
Obviously, the dataset provides a different dtype when iterated with next or with map. Any idea how I can fix this?