我训练了一个神经网络模型,我希望能够很容易地从我的计算机上传一幅图像来预测它的分类。我正在尝试使用以下代码片段将图像上载到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])))
我想使用 cv2.imread 函数将图像转换为像素数组,但上载的文件类型为字节,而此函数需要文件路径。
cv2.imread
我的问题是,有没有办法将上传的图像保存在Colab的文件目录中,以便我可以将其用于 cv2.imread 作为文件路径的功能,或者,是否有其他方法来实现我所寻找的?
非常感谢。
要从内存中读取字节数组,请尝试 cv2.imdecode 。需要使用np将字节转换为numpy数组。frombuffer,然后使用imdecode
img = cv2.imdecode(np.frombuffer(uploaded[fn]), np.uint8), 1)