Skip to content

Commit e842c00

Browse files
authored
Added Chapter 9
1 parent 4824ae3 commit e842c00

9 files changed

Lines changed: 1859 additions & 0 deletions
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
from flask import Flask, request, jsonify, redirect
2+
import os , json
3+
from imageai.Detection import ObjectDetection
4+
5+
model_path = os.getcwd()
6+
7+
PRE_TRAINED_MODELS = ["resnet50_coco_best_v2.0.1.h5"]
8+
9+
10+
# Creating ImageAI objects and loading models
11+
12+
object_detector = ObjectDetection()
13+
object_detector.setModelTypeAsRetinaNet()
14+
object_detector.setModelPath( os.path.join(model_path , PRE_TRAINED_MODELS[0]))
15+
object_detector.loadModel()
16+
object_detections = object_detector.detectObjectsFromImage(input_image='sample.jpg')
17+
18+
# Define model paths and the allowed file extentions
19+
UPLOAD_FOLDER = model_path
20+
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
21+
22+
app = Flask(__name__)
23+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
24+
25+
26+
def allowed_file(filename):
27+
return '.' in filename and \
28+
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
29+
30+
31+
@app.route('/predict', methods=['POST'])
32+
def upload_file():
33+
if request.method == 'POST':
34+
# check if the post request has the file part
35+
if 'file' not in request.files:
36+
print('No file part')
37+
return redirect(request.url)
38+
file = request.files['file']
39+
# if user does not select file, browser also
40+
# submit a empty part without filename
41+
if file.filename == '':
42+
print('No selected file')
43+
return redirect(request.url)
44+
if file and allowed_file(file.filename):
45+
filename = file.filename
46+
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
47+
file.save(file_path)
48+
49+
try:
50+
object_detections = object_detector.detectObjectsFromImage(input_image=file_path)
51+
except Exception as ex:
52+
return jsonify(str(ex))
53+
resp = []
54+
for eachObject in object_detections :
55+
resp.append([eachObject["name"],
56+
round(eachObject["percentage_probability"],3)
57+
]
58+
)
59+
60+
61+
return json.dumps(dict(enumerate(resp)))
62+
63+
if __name__ == "__main__":
64+
app.run(host='0.0.0.0', port=4445)
65+
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
2+
import cv2
3+
import matplotlib
4+
from matplotlib import colors
5+
from matplotlib import pyplot as plt
6+
import numpy as np
7+
from __future__ import division
8+
9+
10+
def show(image):
11+
# Figure size in inches
12+
plt.figure(figsize=(15, 15))
13+
14+
# Show image, with nearest neighbour interpolation
15+
plt.imshow(image, interpolation='nearest')
16+
17+
def show_hsv(hsv):
18+
rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
19+
show(rgb)
20+
21+
def show_mask(mask):
22+
plt.figure(figsize=(10, 10))
23+
plt.imshow(mask, cmap='gray')
24+
25+
def overlay_mask(mask, image):
26+
rgb_mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
27+
img = cv2.addWeighted(rgb_mask, 0.5, image, 0.5, 0)
28+
show(img)
29+
30+
31+
def find_biggest_contour(image):
32+
image = image.copy()
33+
im2,contours, hierarchy = cv2.findContours(image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
34+
35+
contour_sizes = [(cv2.contourArea(contour), contour) for contour in contours]
36+
biggest_contour = max(contour_sizes, key=lambda x: x[0])[1]
37+
38+
mask = np.zeros(image.shape, np.uint8)
39+
cv2.drawContours(mask, [biggest_contour], -1, 255, -1)
40+
return biggest_contour, mask
41+
42+
def circle_countour(image, countour):
43+
image_with_ellipse = image.copy()
44+
ellipse = cv2.fitEllipse(countour)
45+
46+
cv2.ellipse(image_with_ellipse, ellipse, (0,255,0), 2)
47+
return image_with_ellipse
48+
49+
50+
image = cv2.imread('./Downloads/ferrari.jpg')
51+
52+
53+
54+
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
55+
max_dimension = max(image.shape)
56+
scale = 700/max_dimension
57+
image = cv2.resize(image, None, fx=scale,fy=scale)
58+
59+
# Convert from RGB to HSV
60+
image_blur = cv2.GaussianBlur(image, (7, 7), 0)
61+
image_blur_hsv = cv2.cvtColor(image_blur, cv2.COLOR_RGB2HSV)
62+
63+
# filter by color
64+
min_red = np.array([0, 100, 80])
65+
max_red = np.array([10, 256, 256])
66+
mask1 = cv2.inRange(image_blur_hsv, min_red, max_red)
67+
68+
# filter by brigness
69+
min_red = np.array([170, 100, 80])
70+
max_red = np.array([180, 256, 256])
71+
mask2 = cv2.inRange(image_blur_hsv, min_red, max_red)
72+
73+
mask = mask1 + mask2
74+
75+
76+
77+
78+
79+
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15))
80+
mask_closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
81+
mask_clean = cv2.morphologyEx(mask_closed, cv2.MORPH_OPEN, kernel)
82+
83+
84+
85+
86+
big_contour, red_mask = find_biggest_contour(mask_clean)
87+
88+
overlay = overlay_mask(red_mask, image)
89+
90+
circled = circle_countour(overlay, big_contour)
91+
92+
show(circled)
93+
94+
bgr = cv2.cvtColor(circled, cv2.COLOR_RGB2BGR)
95+
96+

Chapter 9/sample.jpg

510 KB
Loading

0 commit comments

Comments
 (0)