如何使用keras.preprocessing从Google Cloud Storage加载图像

3
我正在编写可以在本地或云端进行训练的机器学习代码。我使用keras.preprocessing来加载图像,该库底层使用PIL。对于本地文件,它可以正常工作,但是无法理解Google Cloud Storage路径,例如“gs:// ...”。
以下代码会出现错误: from keras.preprocessing import image image.load_img("gs://myapp-some-bucket/123.png") 错误如下: ".../lib/python2.7/site-packages/keras/preprocessing/image.py", line 320, in load_img img = pil_image.open(path) File .../lib/python2.7/site-packages/PIL/Image.py", line 2530, in open fp = builtins.open(filename, "rb") IOError: [Errno 2] No such file or directory: 'gs://myapp-some-bucket/123.png'
正确的做法是什么?我最终需要将一个包含多张图像的文件夹转换为单个numpy数组(解码并灰度化)。

我不熟悉Keras。它可能不支持直接GCS访问。如果数据集不大,您可以使用预安装的gsutil cli先将数据集复制到VM中。在Python中,您可以调用os.system('gsutil cp YOUR_GCS_FILE .')。 - Guoqing Xu
2个回答

2

我找到了一个替代keras.preprocessing.image.load_img的工具,它可以理解GCS。我还加入了更多代码来读取整个文件夹,并将文件夹中的每张图片转换成单个numpy数组用于训练...

import os
import tensorflow as tf
from tensorflow.python.platform import gfile
filelist = gfile.ListDirectory("gs://myapp-some-bucket")
sess = tf.Session()
with sess.as_default():
   x = np.array([np.array(tf.image.decode_png(tf.read_file(os.path.join(train_files_dir, filename))).eval()) for filename in filelist])

谢谢您的回答。但是由于某些原因,“gfile.ListDirectory”无法找到我的目录。我收到了一个找不到目录的错误。 - Moondra

0

加载图片:

image_path = 'gs://xxxxxxx.jpg'
image = tf.read_file(image_path)
image = tf.image.decode_jpeg(image)
image_array = sess.run(image)

保存图像:

job_dir = 'gs://xxxxxxxx'
image = tf.image.encode_jpeg(image_array)
file_name = 'xxx.jpg'
write_op = tf.write_file(os.path.join(job_dir, file_name), image)
sess.run(write_op)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接