%%time
# model vars
modelPath = './model/preTrainedImageNetGooglenet.onnx'
labelsPath = './model/labels.csv'
hasHeader = 1
#data vars
image_folder = './ImageFolder/'
EXT = ("jfif","jpg")
%%time
!pip install onnx
!pip install onnxruntime
import onnx
import numpy as np
from PIL import Image
import os as os
import matplotlib.pyplot as plt
from onnxruntime import InferenceSession
import csv
%%time
def loadmodel(modelPath,labelsPath,hasHeader):
# define network
# load and check the model
# load the inference module
onnx.checker.check_model(modelPath)
sess = InferenceSession(modelPath)
# Determine the name of the input and output layers
inname = [input.name for input in sess.get_inputs()]
outname = [output.name for output in sess.get_outputs()]
# auxiliary function to load labels file
def extractLabels( filename , hasHeader ):
file = open(filename)
csvreader = csv.reader(file)
if (hasHeader>0):
header = next(csvreader)
#print(header)
rows = []
for row in csvreader:
rows.append(row)
#print(rows)
file.close()
return rows
# Get labels
labels = extractLabels(labelsPath,hasHeader)
# Extract information on the inputSize =(width, heigh) and numChannels = 3(RGB) or 1(Grayscale)
for inp in sess.get_inputs():
inputSize = inp.shape
numChannels = inputSize[1]
inputSize = inputSize[2:4]
return sess,inname,outname,numChannels,inputSize,labels
def getData(image_folder,EXT,inputSize):
def getImagesFromFolder(EXT):
imageList = os.listdir(image_folder)
if (not(isinstance(EXT, list)) and not(isinstance(EXT,tuple))):
ext = [EXT]
fullFilePath = [os.path.join(image_folder, f)
for ext in EXT for f in imageList if os.path.isfile(os.path.join(image_folder, f)) & f.endswith(ext)]
return fullFilePath
def imFile2npArray(imFile,inputSize):
data = np.array([
np.array(
Image.open(fname).resize(inputSize),
dtype=np.int64)
for fname in fullFilePath
])
X=data.transpose(0,3,1,2)
X = X.astype(np.float32)
return X, data
fullFilePath = getImagesFromFolder(EXT)
X, data = imFile2npArray(fullFilePath,inputSize)
return X,data,fullFilePath
%%time
# run code
sess,inname,outname,numChannels,inputSize,labels = loadmodel(modelPath,labelsPath,hasHeader)
X,data,fullFilePath = getData(image_folder,EXT,inputSize)
print("inputSize: " + str(inputSize))
print("numChannels: " + str(numChannels))
print("inputName: ", inname[0])
print("outputName: ", outname[0])
%%time
#data_output = sess.run(outname, {inname: X[0]})
out = sess.run(None, {inname[0]: X})
out=np.asarray(out[0])
print(out.shape)
IND = []
PROB= []
for i in range(out.shape[0]):
ind=np.where(out[i] == np.amax(out[i]))
IND.append(ind[0][0])
PROB.append(out[i,ind[0][0]])
l = [labels[ind] for ind in IND]
print([labels[ind] for ind in IND])
print(IND)
print(PROB)
%%time
plt.figure(figsize=(15,15))
if data.shape[0]>=6:
nPlots=6
subArray=[2,3]
else:
nPlots=data.shape[0]
subArray = [1, nPlots]
for i in range(nPlots):
plt.subplot(subArray[0],subArray[1],i+1)
plt.imshow(data[i])
plt.axis('off')
plt.title(l[i][0] + ' --- ' + str(round(100*PROB[i])) + '%')
plt.show()