Skip to main content

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.

  1. Get response from the image url.
  2. Get the image as byte using ByteIO
  3. Covert the image as Grayscale for prediction and apply appropriate resize.
  4. 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

def loadImage(url):
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)
test_img = img.reshape((1, 784))
img_class = model.predict(test_img)

Comments

Popular posts from this blog

Build a Flask-Python web App

Building a dynamic website made so easy with Python -Flask, a Micro FrameWork which helps us to create the websites like Twitter and even more. Forget about the complicated web programming languages, start learning Python. So where you start, Python or Flask ?. I should say, you have to learn basics of how Python first, just have a look at Python.org