上传图片到google Colab,使用Keras预测分类

Upload image to google Colab, and use Keras to predict the classification

我训练了一个神经网络模型,我希望能够轻松地从我的计算机上传图像以预测其分类。我正在尝试使用以下代码片段将图片上传到 Google Colab:

from google.colab import files

uploaded = files.upload()

for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

我想使用 OpenCV 模块中的 cv2.imread 函数将图像转换为像素数组,但上传的文件类型是字节,而此函数需要文件路径。

我的问题是,有没有一种方法可以将上传的图像保存在 Colab 的文件目录中,以便我可以将其与 cv2.imread 函数一起用作文件路径,或者,是否有另一种方法来实现我的目标在找什么?

谢谢

要从内存中读取字节数组,请尝试 cv2.imdecode。需要使用 np.frombuffer 将字节转换为 numpy 数组,然后使用 imdecode

 img = cv2.imdecode(np.frombuffer(uploaded[fn]), np.uint8), 1)