-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
172 lines (140 loc) · 5.73 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
from __future__ import division, print_function
# coding=utf-8
import sys
import os
import glob
import re
import numpy as np
# Keras
from keras.applications.imagenet_utils import preprocess_input, decode_predictions
from keras.models import load_model
from keras.preprocessing import image
import base64
import io
import matplotlib.pyplot as plt
# Flask utils
from flask import Flask, redirect, url_for, request, render_template
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
from keras.applications.resnet50 import ResNet50
from keras.preprocessing import image
from sklearn.cluster import KMeans
import shutil, glob, os.path
from PIL import Image as pil_image
image.LOAD_TRUNCATED_IMAGES = True
#knn image retrivel
from sklearn.neighbors.unsupervised import NearestNeighbors
from PIL import Image
from tensorflow.keras.preprocessing import image
# Model saved with Keras model.save()
MODEL_PATH = 'models/garbage_model.h5'
# Load your trained model
model = load_model(MODEL_PATH)
#model._make_predict_function() # Necessary
print('Model loaded. Start serving...')
# Check https://keras.io/applications/
#model = ResNet50(weights='imagenet')
#model.save('models')
#print('Model loaded. Check http://127.0.0.1:5000/')
# Variables
imdir = 'C:/Users/root/Documents/sample/deploy_sample/uploads/'
number_clusters = 3
filelist = glob.glob(os.path.join(imdir, '*.jpeg'))
#filelist = glob.glob(os.path.join(imdir ,'*.' + e)) for e in ext
# Define a flask app
app = Flask(__name__)
def model_predict(img_path, model):
img = image.load_img(img_path, target_size=(224, 224))
# Preprocessing the image
x = image.img_to_array(img)
# x = np.true_divide(x, 255)
x = np.expand_dims(x, axis=0)
# Be careful how your trained model deals with the input
# otherwise, it won't make correct prediction!
x = preprocess_input(x, mode='caffe')
preds = model.predict(x)
return preds
#load images as np arrays
def load_data(fpath):
img=Image.open(fpath).resize((224,224)) # resize to 224x224 for training purposes
img = np.asarray(img, dtype='float32')
return img
@app.route('/', methods=['GET'])
def index():
# Main page
return render_template('index.html')
@app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
# Get the file from post request
f = request.files['file']
# Save the file to ./uploads
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
# Make prediction
output_class = ["batteries", "cloth", "e-waste", "glass", "light bulbs", "metallic", "organic", "paper", "plastic"]
preds = model_predict(file_path, model)
print(preds)
pred_class = output_class[np.argmax(preds)]
pred_class_percent = round(np.max(preds) * 100, 2)
result = 'It is '+ pred_class + ' waste' # Convert to string
pred_class = ' with '+ str(pred_class_percent) + '% confidence'
#k-nn for recommending
filelist.sort()
featurelist = []
for i, imagepath in enumerate(filelist):
print(" Status: %s / %s" %(i, len(filelist)), end="\r")
img = image.load_img(imagepath, target_size=(224, 224))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
features = np.array(model.predict(img_data))
featurelist.append(features.flatten())
nei_clf = NearestNeighbors(metric="euclidean")
nei_clf.fit(featurelist)
code = model_predict(file_path, model)
(distances,),(idx,) = nei_clf.kneighbors(code,n_neighbors=3)
#all images are loaded as np arrays
images=[]
labels=[]
j=1
for i,image_path in enumerate(filelist):
images.append(load_data(image_path))
images = np.asarray(images) # all of the images are converted to np array of (1360,224,224,3)
print(distances,images[idx])
print(images[idx].shape)
final_result = result + pred_class
image_save = Image.fromarray((np.array(images[0]) * 255).astype(np.uint8))
#image_save = Image.fromarray(images[idx], "RGB")
image_save.save('out.jpg')
image_output = os.path.join(basepath, 'out.jpg')
immg = '<img src="'+image_output+'" style="height: 132px; width: 132px;">'
#return render_template('index.html', filename=image_output)
return final_result
return None
@app.route('/recommend', methods=['POST'])
def recommend():
#if request.method == 'POST':
f = request.files['file']
basepath = os.path.dirname(__file__)
file_path = os.path.join(basepath, 'uploads', secure_filename(f.filename))
f.save(file_path)
#custer for recommending
filelist.sort()
featurelist = []
for i, imagepath in enumerate(filelist):
print(" Status: %s / %s" %(i, len(filelist)), end="\r")
img = image.load_img(imagepath, target_size=(224, 224))
img_data = image.img_to_array(img)
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
features = np.array(model.predict(img_data))
featurelist.append(features.flatten())
nei_clf = NearestNeighbors(metric="euclidean")
nei_clf.fit(featurelist)
distances,neighbors = get_similar(file_path,n_neighbors=3)
return 'hello recommender'
if __name__ == '__main__':
app.run(debug=True)