我创建了一个简单的CNN来识别三种鱼。我试图使用CNN来分类训练集或验证集中未包含的图像。该图像名为grunts-saltwater.jpg,存储在Google Drive上。以下是使用现有CNN模型进行预测的代码:
grunts_url = "https://drive.google.com/file/d/1zuA6T_0a9mOUvNWHQ1OACPLaZMCtbIZd/view?usp=sharing"grunts_path = tf.keras.utils.get_file('grunts-saltwater', origin=grunts_url)img = keras.preprocessing.image.load_img( grunts_path, target_size=(img_height, img_width))img_array = keras.preprocessing.image.img_to_array(img)img_array = tf.expand_dims(img_array, 0) # Create a batchpredictions = model.predict(img_array)score = tf.nn.softmax(predictions[0])print( "This image most likely belongs to {} with a {:.2f} percent confidence." .format(class_names[np.argmax(score)], 100 * np.max(score)))
然而,我得到了以下错误:
Downloading data from https://drive.google.com/file/d/1zuA6T_0a9mOUvNWHQ1OACPLaZMCtbIZd/view?usp=sharing 8192/Unknown - 0s 0us/step---------------------------------------------------------------------------UnidentifiedImageError Traceback (most recent call last)<ipython-input-217-d031443047e1> in <module>() 3 4 img = keras.preprocessing.image.load_img(----> 5 grunts_path, target_size=(img_height, img_width)) 6 7 img_array = keras.preprocessing.image.img_to_array(img)2 frames/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/preprocessing/image.py in load_img(path, grayscale, color_mode, target_size, interpolation) 299 """ 300 return image.load_img(path, grayscale=grayscale, color_mode=color_mode,--> 301 target_size=target_size, interpolation=interpolation) 302 303 /usr/local/lib/python3.6/dist-packages/keras_preprocessing/image/utils.py in load_img(path, grayscale, color_mode, target_size, interpolation) 112 'The use of `load_img` requires PIL.') 113 with open(path, 'rb') as f:--> 114 img = pil_image.open(io.BytesIO(f.read())) 115 if color_mode == 'grayscale': 116 # if image is not already an 8-bit, 16-bit or 32-bit grayscale image/usr/local/lib/python3.6/dist-packages/PIL/Image.py in open(fp, mode) 2860 warnings.warn(message) 2861 raise UnidentifiedImageError(-> 2862 "cannot identify image file %r" % (filename if filename else fp) 2863 ) 2864 UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x7f9002c637d8>
您能帮我解决这个问题吗?谢谢。
回答:
这是因为图像的Google Drive链接现在是一个查看链接,而不是可下载的链接。如果它是被共享的,您可以将其转换为可下载的链接,以便HTTP客户端可以下载它。
转换为可下载链接
您共享的图像ID是1zuA6T_0a9mOUvNWHQ1OACPLaZMCtbIZd
,因此使用链接"https://docs.google.com/uc?export=download&id=1zuA6T_0a9mOUvNWHQ1OACPLaZMCtbIZd"
修复后的代码:
grunts_url = "https://docs.google.com/uc?export=download&id=1zuA6T_0a9mOUvNWHQ1OACPLaZMCtbIZd"grunts_path = tf.keras.utils.get_file('grunts-saltwater', origin=grunts_url)img = keras.preprocessing.image.load_img(grunts_path, target_size=(100, 100))