Using Image url in Keras image classification
How to load an image in Keras for machine learning from a url ?
For loading image in Keras we used to write code like this
img = keras.utils.load_img(path="OIP.jpg",
color_mode = "grayscale",target_size=(28,28,1))
How about using a image URL instead of the above code?
Need to perform couple of things.
- Get response from the image url.
- Get the image as byte using ByteIO
- Covert the image as Grayscale for prediction and apply appropriate resize.
- Finally covert the image into a NumPy array.
Let's wrap all these in a function.
from tensorflow import keras
from io import BytesIO
from PIL import Image
import requests
from PIL import Image
import requests
response = requests.get(url)
img_bytes = BytesIO(response.content)
img = Image.open(img_bytes)
img = img.convert('L')
# img = img.convert('1')
# img = img.convert('RGB')
img = img.resize((28, 28), Image.NEAREST)
img = keras.utils.img_to_array(img)
return img
Before using the image for prediction, we need to reshape the image.
url = 'https://edwin-de-jong.github.io/blog/mnist-sequence-data/fig/5.png'
img = loadImage(url)
img = loadImage(url)
test_img = img.reshape((1, 784))
img_class = model.predict(test_img)
img_class = model.predict(test_img)
Comments
Post a Comment