Skip to content

Instantly share code, notes, and snippets.

@beaulian
Forked from johnolafenwa/imagenet_inference.py
Created December 10, 2018 13:59
Show Gist options
  • Save beaulian/0239741e9b99e6b06e0477b6894cb470 to your computer and use it in GitHub Desktop.
Save beaulian/0239741e9b99e6b06e0477b6894cb470 to your computer and use it in GitHub Desktop.
# Import needed packages
import torch
import torch.nn as nn
from torchvision.transforms import transforms
import matplotlib.pyplot as plt
import numpy as np
from torch.autograd import Variable
from torchvision.models import squeezenet1_1
import torch.functional as F
import requests
import shutil
from io import open
import os
from PIL import Image
import json
""" Instantiate model, this downloads tje 4.7 mb squzzene the first time it is called.
To use with your own model, re-define your trained networks ad load weights as below
checkpoint = torch.load("pathtosavemodel")
model = SimpleNet(num_classes=10)
model.load_state_dict(checkpoint)
model.eval()
"""
model = squeezenet1_1(pretrained=True)
model.eval()
def predict_image(image_path):
print("Prediction in progress")
image = Image.open(image_path)
# Define transformations for the image, should (note that imagenet models are trained with image size 224)
transformation = transforms.Compose([
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
# Preprocess the image
image_tensor = transformation(image).float()
# Add an extra batch dimension since pytorch treats all images as batches
image_tensor = image_tensor.unsqueeze_(0)
if torch.cuda.is_available():
image_tensor.cuda()
# Turn the input into a Variable
input = Variable(image_tensor)
# Predict the class of the image
output = model(input)
index = output.data.numpy().argmax()
return index
if __name__ == "__main__":
imagefile = "image.png"
imagepath = os.path.join(os.getcwd(), imagefile)
# Donwload image if it doesn't exist
if not os.path.exists(imagepath):
data = requests.get(
"https://github.com/OlafenwaMoses/ImageAI/raw/master/images/3.jpg", stream=True)
with open(imagepath, "wb") as file:
shutil.copyfileobj(data.raw, file)
del data
index_file = "class_index_map.json"
indexpath = os.path.join(os.getcwd(), index_file)
# Donwload class index if it doesn't exist
if not os.path.exists(indexpath):
data = requests.get('https://github.com/OlafenwaMoses/ImageAI/raw/master/imagenet_class_index.json')
with open(indexpath, "w", encoding="utf-8") as file:
file.write(data.text)
class_map = json.load(open(indexpath))
# run prediction function annd obtain prediccted class index
index = predict_image(imagepath)
prediction = class_map[str(index)][1]
print("Predicted Class ", prediction)
@lamoidfl
Copy link

lamoidfl commented Jul 8, 2019

I'm terribly sorry to bother you with a newby question, but I'm stuck. When I try to run this program, imagenet_inference.py, I get the following result:

(dl) >python imagenet_inference.py
Traceback (most recent call last):
File "imagenet_inference.py", line 90, in
class_map = json.load(open(indexpath))
File "C:\ProgramData\Anaconda3\envs\dl\lib\json_init_.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\ProgramData\Anaconda3\envs\dl\lib\json_init_.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda3\envs\dl\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\ProgramData\Anaconda3\envs\dl\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 7 column 1 (char 6)

I am probably doing incorrectly something simple. But I cannot figure it out. Any help is greatly appreciated!

@beaulian
Copy link
Author

beaulian commented Jul 9, 2019

I'm terribly sorry to bother you with a newby question, but I'm stuck. When I try to run this program, imagenet_inference.py, I get the following result:

(dl) >python imagenet_inference.py
Traceback (most recent call last):
File "imagenet_inference.py", line 90, in
class_map = json.load(open(indexpath))
File "C:\ProgramData\Anaconda3\envs\dl\lib\json__init__.py", line 296, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\ProgramData\Anaconda3\envs\dl\lib\json__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda3\envs\dl\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\ProgramData\Anaconda3\envs\dl\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 7 column 1 (char 6)

I am probably doing incorrectly something simple. But I cannot figure it out. Any help is greatly appreciated!

Because the link "https://github.com/OlafenwaMoses/ImageAI/raw/master/imagenet_class_index.json" does not exist now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment