Skip to content

Commit 397e49b

Browse files
committed
upload source new
1 parent c92381e commit 397e49b

File tree

7 files changed

+172
-95
lines changed

7 files changed

+172
-95
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from keras.models import model_from_json
2+
from PIL import Image
3+
import numpy as np
4+
import os
5+
6+
class Cifar10Classifier:
7+
cifar10_model = None
8+
9+
def __init__(self):
10+
# load and configure the cifar19 classifier model
11+
self.cifar10_model = model_from_json(
12+
open(os.path.join('../keras_image_classifier/models', 'cnn_cifar10_architecture.json')).read())
13+
self.cifar10_model.load_weights(os.path.join('../keras_image_classifier/models', 'cnn_cifar10_weights.h5'))
14+
self.cifar10_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
15+
16+
def predict(self, filename):
17+
img = Image.open(filename)
18+
img = img.resize((32, 32), Image.ANTIALIAS)
19+
20+
input = np.asarray(img)
21+
input = input.astype('float32') / 255
22+
input = np.expand_dims(input, axis=0)
23+
24+
print(input.shape)
25+
26+
predicted_class = self.cifar10_model.predict_classes(input)[0]
27+
28+
labels = [
29+
"airplane",
30+
"automobile",
31+
"bird",
32+
"cat",
33+
"deer",
34+
"dog",
35+
"frog",
36+
"horse",
37+
"ship",
38+
"truck"
39+
]
40+
return predicted_class, labels[predicted_class]
41+
42+
def run_test(self):
43+
print(self.predict('../keras_image_classifier/bi_classifier_data/training/cat/cat.2.jpg'))
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from keras.models import model_from_json
2+
import os
3+
from PIL import Image
4+
import numpy as np
5+
6+
7+
class BiClassifier(object):
8+
bi_model = None
9+
10+
def __init__(self):
11+
# load and configure the binary classifier model for "cats vs dogs"
12+
self.bi_model = model_from_json(
13+
open(os.path.join('../keras_image_classifier/models', 'cnn_bi_classifier_architecture.json')).read())
14+
self.bi_model.load_weights(os.path.join('../keras_image_classifier/models', 'cnn_bi_classifier_weights.h5'))
15+
self.bi_model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
16+
17+
def run_test(self):
18+
print(self.predict('../keras_image_classifier/bi_classifier_data/training/cat/cat.2.jpg'))
19+
20+
def predict(self, filename):
21+
img = Image.open(filename)
22+
img = img.resize((150, 150), Image.ANTIALIAS)
23+
24+
input = np.asarray(img)
25+
input = input.astype('float32') / 255
26+
input = np.expand_dims(input, axis=0)
27+
28+
print(input.shape)
29+
30+
output = self.bi_model.predict(input)
31+
32+
probability_of_a_dog = output[0][0]
33+
predicted_label = ("Dog" if probability_of_a_dog > 0.5 else "Cat")
34+
return probability_of_a_dog, predicted_label

keras_image_classifier_web/flaskr.py

Lines changed: 46 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import os
2-
from keras.models import model_from_json
3-
from PIL import Image
4-
import numpy as np
2+
from keras_image_classifier_web.cnn_bi_classifier import BiClassifier
3+
from keras_image_classifier_web.cifar10_classifier import Cifar10Classifier
4+
from keras_image_classifier_web.vgg16_classifier import VGG16Classifier
55

66
from flask import Flask, request, session, g, redirect, url_for, abort, \
77
render_template, flash
@@ -18,68 +18,14 @@
1818
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
1919
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
2020

21-
# load and configure the binary classifier model for "cats vs dogs"
22-
bi_model = model_from_json(
23-
open(os.path.join('../keras_image_classifier/models', 'cnn_bi_classifier_architecture.json')).read())
24-
bi_model.load_weights(os.path.join('../keras_image_classifier/models', 'cnn_bi_classifier_weights.h5'))
21+
bi_classifier = BiClassifier()
22+
bi_classifier.run_test()
2523

26-
bi_model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
27-
28-
# load and configure the cifar19 classifier model
29-
cifar10_model = model_from_json(
30-
open(os.path.join('../keras_image_classifier/models', 'cnn_cifar10_architecture.json')).read())
31-
cifar10_model.load_weights(os.path.join('../keras_image_classifier/models', 'cnn_cifar10_weights.h5'))
32-
33-
cifar10_model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
34-
35-
36-
def predict_binary(filename):
37-
img = Image.open(filename)
38-
img = img.resize((150, 150), Image.ANTIALIAS)
39-
40-
input = np.asarray(img)
41-
input = input.astype('float32') / 255
42-
input = np.expand_dims(input, axis=0)
43-
44-
print(input.shape)
45-
46-
output = bi_model.predict(input)
47-
48-
probability_of_a_dog = output[0][0]
49-
predicted_label = ("Dog" if probability_of_a_dog > 0.5 else "Cat")
50-
return probability_of_a_dog, predicted_label
51-
52-
53-
def predict_cifar10(filename):
54-
img = Image.open(filename)
55-
img = img.resize((32, 32), Image.ANTIALIAS)
56-
57-
input = np.asarray(img)
58-
input = input.astype('float32') / 255
59-
input = np.expand_dims(input, axis=0)
60-
61-
print(input.shape)
62-
63-
predicted_class = cifar10_model.predict_classes(input)[0]
64-
65-
labels = [
66-
"airplane",
67-
"automobile",
68-
"bird",
69-
"cat",
70-
"deer",
71-
"dog",
72-
"frog",
73-
"horse",
74-
"ship",
75-
"truck"
76-
]
77-
return predicted_class, labels[predicted_class]
78-
79-
80-
predict_binary('../keras_image_classifier/bi_classifier_data/training/cat/cat.2.jpg')
81-
predict_cifar10('../keras_image_classifier/bi_classifier_data/training/cat/cat.2.jpg')
24+
cifar10_classifier = Cifar10Classifier()
25+
cifar10_classifier.run_test()
8226

27+
vgg16_classifier = VGG16Classifier()
28+
vgg16_classifier.run_test()
8329

8430

8531
@app.route('/')
@@ -92,6 +38,24 @@ def allowed_file(filename):
9238
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
9339

9440

41+
def store_uploaded_image(action):
42+
# check if the post request has the file part
43+
if 'file' not in request.files:
44+
flash('No file part')
45+
return redirect(request.url)
46+
file = request.files['file']
47+
# if user does not select file, browser also
48+
# submit a empty part without filename
49+
if file.filename == '':
50+
flash('No selected file')
51+
return redirect(request.url)
52+
if file and allowed_file(file.filename):
53+
filename = secure_filename(file.filename)
54+
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
55+
return redirect(url_for(action,
56+
filename=filename))
57+
58+
9559
@app.route('/about', methods=['GET'])
9660
def about():
9761
return 'about us'
@@ -100,61 +64,48 @@ def about():
10064
@app.route('/cats_vs_dogs', methods=['GET', 'POST'])
10165
def cats_vs_dogs():
10266
if request.method == 'POST':
103-
# check if the post request has the file part
104-
if 'file' not in request.files:
105-
flash('No file part')
106-
return redirect(request.url)
107-
file = request.files['file']
108-
# if user does not select file, browser also
109-
# submit a empty part without filename
110-
if file.filename == '':
111-
flash('No selected file')
112-
return redirect(request.url)
113-
if file and allowed_file(file.filename):
114-
filename = secure_filename(file.filename)
115-
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
116-
return redirect(url_for('cats_vs_dogs_result',
117-
filename=filename))
67+
return store_uploaded_image('cats_vs_dogs_result')
11868
return render_template('cats_vs_dogs.html')
11969

12070

12171
@app.route('/cifar10', methods=['GET', 'POST'])
12272
def cifar10():
12373
if request.method == 'POST':
124-
# check if the post request has the file part
125-
if 'file' not in request.files:
126-
flash('No file part')
127-
return redirect(request.url)
128-
file = request.files['file']
129-
# if user does not select file, browser also
130-
# submit a empty part without filename
131-
if file.filename == '':
132-
flash('No selected file')
133-
return redirect(request.url)
134-
if file and allowed_file(file.filename):
135-
filename = secure_filename(file.filename)
136-
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
137-
return redirect(url_for('cifar10_result',
138-
filename=filename))
74+
return store_uploaded_image('cifar10_result')
13975
return render_template('cifar10.html')
14076

14177

78+
@app.route('/vgg16', methods=['GET', 'POST'])
79+
def vgg16():
80+
if request.method == 'POST':
81+
return store_uploaded_image('vgg16_result')
82+
return render_template('vgg16.html')
83+
84+
14285
@app.route('/cats_vs_dogs_result/<filename>')
14386
def cats_vs_dogs_result(filename):
14487
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
145-
probability_of_dog, predicted_label = predict_binary(filepath)
88+
probability_of_dog, predicted_label = bi_classifier.predict(filepath)
14689
return render_template('cats_vs_dogs_result.html', filename=filename,
14790
probability_of_dog=probability_of_dog, predicted_label=predicted_label)
14891

14992

15093
@app.route('/cifar10_result/<filename>')
15194
def cifar10_result(filename):
15295
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
153-
predicted_class, predicted_label = predict_cifar10(filepath)
96+
predicted_class, predicted_label = cifar10_classifier.predict(filepath)
15497
return render_template('cifar10_result.html', filename=filename,
15598
predicted_class=predicted_class, predicted_label=predicted_label)
15699

157100

101+
@app.route('/vgg16_result/<filename>')
102+
def vgg16_result(filename):
103+
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
104+
top3 = vgg16_classifier.predict(filepath)
105+
return render_template('vgg16_result.html', filename=filename,
106+
top3=top3)
107+
108+
158109
@app.route('/images/<filename>')
159110
def get_image(filename):
160111
return send_from_directory(app.config['UPLOAD_FOLDER'],

keras_image_classifier_web/templates/classifiers.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
<ul class=entries>
44
<li><a href="{{ url_for('cats_vs_dogs') }}">Cats vs Dogs</a></li>
55
<li><a href="{{ url_for('cifar10') }}">CIFAR-10</a></li>
6+
<li><a href="{{ url_for('vgg16') }}">VGG-16</a></li>
67
</ul>
78
{% endblock %}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{% extends "layout.html" %}
2+
{% block body %}
3+
<p>Upload your picture and we will try to what it is using VGG16 classifier</p>
4+
<form method=post enctype=multipart/form-data>
5+
<p><input type=file name=file>
6+
<input type=submit value=Upload>
7+
</form>
8+
{% endblock %}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{% extends "layout.html" %}
2+
{% block body %}
3+
<img src="/images/{{ filename }}" />
4+
<br />
5+
<hr />
6+
Below is my top 3 guesses of what is inside your picture:
7+
<ol>
8+
{% for pred in top3 %}
9+
<li>{{ pred[1] }} ({{ pred[2] }})</li>
10+
{% endfor %}
11+
</ol>
12+
<hr />
13+
<a href="{{ url_for('vgg16') }}">Try another picture</a>
14+
{% endblock %}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from keras.models import Model
2+
from keras.applications.vgg16 import VGG16, preprocess_input, decode_predictions
3+
from keras.optimizers import SGD
4+
from PIL import Image
5+
from keras.preprocessing.image import img_to_array
6+
import numpy as np
7+
8+
9+
class VGG16Classifier:
10+
model = None
11+
12+
def __init__(self):
13+
self.model = VGG16(include_top=True, weights='imagenet')
14+
self.model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy'])
15+
16+
def predict(self, filename):
17+
img = Image.open(filename)
18+
img = img.resize((224, 224), Image.ANTIALIAS)
19+
input = img_to_array(img)
20+
input = np.expand_dims(input, axis=0)
21+
input = preprocess_input(input)
22+
output = decode_predictions(self.model.predict(input), top=3)
23+
return output[0]
24+
25+
def run_test(self):
26+
print(self.predict('../keras_image_classifier/bi_classifier_data/training/cat/cat.3.jpg'))

0 commit comments

Comments
 (0)