def __init__(self, frame, canvas=None, x=0, y=0, w=None, h=None, type_=EyeType.UNDEFINED, padding=0): x += padding y += padding w = (w if w else frame.shape[1]) - padding * 2 h = (h if h else frame.shape[0]) - padding * 2 self.x = x self.y = y self.w = w self.h = h self.coords = (x, y, w, h) self.centroid = (x + w / 2, y + h / 2) self.type = type_ self.frame = np.copy(frame[y:y + h, x:x + w]) self.gray = cv2.cvtColor(frame[y:y + h, x:x + w], cv2.COLOR_BGR2GRAY) canvas = canvas if canvas is not None else np.copy(frame) self.canvas = canvas[y:y + h, x:x + w] self.moments = None self.momentVectors = None self.iris = Iris(self)
async def post_auth_hook(authenticator, handler, authentication): iris = Iris() userdata = await iris.query_user(authentication["name"]) if authentication["auth_state"] is None: authentication["auth_state"] = {} authentication["auth_state"]["userdata"] = userdata return authentication
def test_iris_scikit_learn_comparison(): """ This test compares the created Naive Bayes classifier implementation with scikit-learn library using iris.csv dataset. """ print('\n===============================') print('=== PROJECT IMPLEMENTATION ====') print('===============================') seed(1) iris = Iris() iris.data_preprocessing() project_efficiency_percent = iris.calculate_accuracy(n_folds=2) print('\n===============================') print('======== SCIKIT-LEARN =========') print('===============================') X, y = load_iris(return_X_y=True) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0) gnb = GaussianNB() y_pred = gnb.fit(X_train, y_train).predict(X_test) num_of_points = 75 mislabeled_points = (y_test != y_pred).sum() sklearn_efficiency_percent = ( (num_of_points - mislabeled_points) / num_of_points) * 100 print( f'\n\nCalculating the scikit-learn algorithm accuracy with iris.csv dataset...' ) print( f'\nNumber of mislabeled points out of a total {num_of_points} points : {mislabeled_points}' ) print(f'\nAlgorithm efficiency: {round(sklearn_efficiency_percent, 5)} %') assert (project_efficiency_percent - sklearn_efficiency_percent) < 10
async def task_handler(data:Iris, background_tasks: BackgroundTasks): data = data.dict() print("in the prediction") sepal_length = data['sepal_length'] sepal_width = data['sepal_width'] petal_length = data['petal_length'] petal_width = data['petal_width'] new_task = Job() jobs[new_task.uid] = new_task background_tasks.add_task(start_modelling_task, new_task.uid, [sepal_length, sepal_width, petal_length, petal_width]) return new_task
def __init__(self, landmarks, frame, side): self.side = side self.frame = frame self.scale = 1 self.eye_points = self._extract_eye_points(landmarks) self.bbox = cv2.boundingRect(self.eye_points) self.eye_region, self.eye_origin = self._extract_eye_region( frame_padding=2) self.mask = self._make_mask() left, right = self._generate_masked_gradient() self.iris = Iris(left, right, self.eye_region, self.mask) self.eye_corner, self.eye_width = self._extract_eye_corners() self.center = np.array(self._calculate_center()) self.relative_center = self._calculate_relative_center()
async def predict( data: Iris ): # Declare it as a parameter after Iris data model been created # convert Iris object into dictionary data = data.dict() print("in the prediction") # There are different way of input data # another way is to input as csv file using: fastapi.UploadFile sepal_length = data['sepal_length'] sepal_width = data['sepal_width'] petal_length = data['petal_length'] petal_width = data['petal_width'] prediction = await model( [sepal_length, sepal_width, petal_length, petal_width]) print("prediction is done") # can control the return by specify the response_model inside @app.post() decorator return {"prediction": str(prediction)}
from __future__ import absolute_import, division, print_function import os import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() from iris import Iris iris = Iris() model = iris.model optimizer = tf.train.AdamOptimizer(learning_rate=0.001) checkpoint_dir = './iris_model' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") root = tfe.Checkpoint(optimizer=optimizer, model=model, optimizer_step=tf.train.get_or_create_global_step()) root.restore(tf.train.latest_checkpoint(checkpoint_dir)) iris.test()
from iris import Iris from fastapi import FastAPI, Query from typing import List from pydantic import BaseModel import json app = FastAPI(debug=True) iris = Iris() @app.get('/') def proper_root(): return {'ERROR': 'Use GET /predict instead of root route!'} @app.get('/predict/') def predict(features=Query(None)): features = json.loads(features) prediction = iris.classify(features) return {'results': prediction}
from __future__ import absolute_import, division, print_function import os import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() from iris import Iris iris = Iris() model = iris.model optimizer = tf.train.AdamOptimizer(learning_rate=0.001) checkpoint_dir = './iris_model' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") root = tfe.Checkpoint(optimizer=optimizer, model=model, optimizer_step=tf.train.get_or_create_global_step()) root.restore(tf.train.latest_checkpoint(checkpoint_dir)) data_array = [] while True: data = (input("Please enter features to predict (type 'exit' to stop):\n")) if data == 'exit': break data = data.split(",") data_array.append([float(i) for i in data]) if len(data_array) > 0:
from iris import Iris, IrisValue from collections import defaultdict import fileinput iris = Iris() # here we simply add two integers, result will be appended to # result list in enviornment context @iris.register("add {n1:Int} and {n2:Int}") def add(n1, n2): return n1 + n2 # so here we add a new named variable to enviornment context that # holds the result @iris.register("add {n1:Int} and {n2:Int} to var") def add_named(n1, n2): return IrisValue(n1 + n2, name="n1_and_n2") # demonstrate lookup of variable from environment @iris.register("sum {lst:List}") def sum1(lst): return sum(lst) @iris.register("count {lst:List}") def count1(lst): counts = defaultdict(int) for x in lst:
from iris import Iris app = Iris() app.static('.') app.listen()
from __future__ import absolute_import, division, print_function import os import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.contrib.eager as tfe tf.enable_eager_execution() from iris import Iris global_step = tf.train.get_or_create_global_step() summary_writer = tf.contrib.summary.create_file_writer( 'iris_model', flush_millis=10000) with summary_writer.as_default(), tf.contrib.summary.always_record_summaries(): iris = Iris() trained_iris = iris.train() iris.graph(trained_iris, 'test_graphs') model = iris.model optimizer = tf.train.AdamOptimizer(learning_rate=0.001) checkpoint_dir = './iris_model' checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt") root = tfe.Checkpoint(optimizer=optimizer, model=model, optimizer_step=tf.train.get_or_create_global_step()) root.save(file_prefix=checkpoint_prefix) tf.contrib.summary.scalar("loss", my_loss)
def main(): iris = Iris("https://cdn.chotot.com", "73757368690a", "626164626f79640a") url = iris.gen_url("2664732968888824287.jpg", "raw") print(url) unirest.get(url, callback=prefetch_images_callback)
def setUp(self): self.iris = Iris()
class IrisTest(tf.test.TestCase): def setUp(self): self.iris = Iris() def test_download_function(self): filepath = self.iris.download_data()[-17:] self.assertAllEqual(filepath, 'iris_training.csv') def test_download_test_data_function(self): filepath = self.iris.download_test_data()[-13:] self.assertAllEqual(filepath, 'iris_test.csv') def test_format_data_features_and_label_are_tensors(self): features, label, dataset = self.iris.format_data( self.iris.download_data()) self.assertTrue(isinstance(features[0], tf.Tensor)) self.assertTrue(isinstance(label[0], tf.Tensor)) def test_test_function_returns_accuracy(self): test_accuracy_result = self.iris.test() self.assertAllEqual(test_accuracy_result[-1:], '%') def test_train_function_adds_to_loss_and_accuracy_array(self): train_loss_results, train_accuracy_results = self.iris.train() self.assertAllEqual(len(train_loss_results), 201) self.assertAllEqual(len(train_accuracy_results), 201) def test_predict_function(self): self.iris.train() possible_answers = [ 'Example 1 prediction: Iris setosa', 'Example 1 prediction: Iris versicolor', 'Example 1 prediction: Iris virginica' ] predictions = self.iris.predict([[5.1, 3.3, 1.7, 0.5]]) self.assertTrue(predictions in possible_answers) def test_graph_creates_file(self): self.iris.graph([[3, 2, 4, 5], [2, 7, 1, 0]], 'test_graphs') my_file = Path('./test_graphs/figure.png') self.assertTrue(my_file.is_file())
class Eye(object): """Short summary. Args: x (int): x coordinate of the eye (top-left corner) in the face frame. y (int): y coordinate of the eye (top-left corner) in the face frame. w (int): width of the eye in the face frame. h (int): height of the eye in the face frame. frame (np.array): Original face frame onto which the eye has been identified canvas (np.array): Face frame we can draw on type_ (EyeType): Either left or right or undefined yet Attributes: coords (int, int, int, int): (x, y, w, h) centroid (float, float): Center of the eye gray (np.array): Gray-scale version of the eye frame moments (np.array): Moments of our region of interest momentVectors (np.array): Vector moments of our region of interest x y w h frame canvas COLORS (dict): Color associated with each EyeType """ COLORS = { EyeType.UNDEFINED: (255, 255, 255), EyeType.LEFT: (0, 255, 255), EyeType.RIGHT: (0, 0, 255), } def __init__(self, frame, canvas=None, x=0, y=0, w=None, h=None, type_=EyeType.UNDEFINED, padding=0): x += padding y += padding w = (w if w else frame.shape[1]) - padding * 2 h = (h if h else frame.shape[0]) - padding * 2 self.x = x self.y = y self.w = w self.h = h self.coords = (x, y, w, h) self.centroid = (x + w / 2, y + h / 2) self.type = type_ self.frame = np.copy(frame[y:y + h, x:x + w]) self.gray = cv2.cvtColor(frame[y:y + h, x:x + w], cv2.COLOR_BGR2GRAY) canvas = canvas if canvas is not None else np.copy(frame) self.canvas = canvas[y:y + h, x:x + w] self.moments = None self.momentVectors = None self.iris = Iris(self) def distanceToPoint(self, point): """Computes the distance between the point and the eye centroid Args: point (np.array 2): 2d coordinates of the given point Returns: float: Distance to the eye centroid """ return np.sum(np.power(point - np.array(list(self.centroid)), 2)) def getLeft(self): return self.x def getRight(self): return self.x + self.w def getTop(self): return self.y def getBot(self): return self.y + self.h def getTopLeft(self): return (self.x, self.y) def getBotRight(self): return (self.x + self.w, self.y + self.h) def draw(self, face): """Draw a rectangle around the eye and indicates its side. Args: face (Face): Face on which canvas the eye info will be drawn """ cv2.rectangle(face.canvas, self.getTopLeft(), self.getBotRight(), self.COLORS[self.type], 2) cv2.putText(face.canvas, self.type.value, (self.getLeft(), self.getBot() + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.5, self.COLORS[self.type], 1) self.iris.draw(face) def computeMoments(self): """Computes the moments of this eye. Returns: np.array: Moments """ self.moments = cv2.moments(self.gray) return self.moments def computeMomentVectors(self): """Evaluates the 7 moment invariants defined by Hu Returns: np.array: Ordered vector moments """ self.computeMoments() mu = {} for key, value in self.moments.items(): if 'nu' in key: mu[key.replace('nu', '')] = value mvs = [None] * 7 mvs[0] = mu['02'] * mu['20'] mvs[1] = (mu['02'] - mu['20'])**2 + 4 * mu['11'] mvs[2] = (mu['30'] - 3 * mu['12'])**2 + (+3 * mu['21'] - mu['03'])**2 mvs[3] = (mu['30'] + mu['12'])**2 + (mu['21'] + mu['03'])**2 mvs[4] = (mu['30']-3*mu['12'])*(mu['30']+mu['12'])\ *((mu['30']+mu['12'])**2-3*(mu['21']+mu['03'])**2)\ +(3*mu['21']-mu['03'])*(mu['03']+mu['21'])\ *(3*(mu['12']+mu['30'])**2-(mu['03']+mu['21'])**2) mvs[5] = (mu['02']-mu['20'])*((mu['30']+mu['12'])**2-(mu['21']+mu['03'])**2)\ +4*(mu['30']+mu['12'])*(mu['21']+mu['03']) mvs[6] = (3*mu['21']-mu['03'])*(mu['30']+mu['12'])\ *((mu['30']+mu['12'])**2-3*(mu['21']+mu['03'])**2)\ -(mu['21']+mu['03'])*(mu['30']-3*mu['12'])\ *(3*(mu['30']+mu['12'])**2-(mu['21']+mu['03'])**2) self.momentVectors = np.array(mvs) return self.momentVectors