{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "fb70944c", "metadata": {}, "outputs": [ { "ename": "ModuleNotFoundError", "evalue": "No module named 'simplejson'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mModuleNotFoundError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m~\\AppData\\Local\\Temp/ipykernel_23568/1068728291.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mflask\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mFlask\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mrequest\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mResponse\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[1;32mimport\u001b[0m \u001b[0msimplejson\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mtensorflow\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mvisualization_utils\u001b[0m \u001b[1;32mas\u001b[0m \u001b[0mvis_util\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[1;32mfrom\u001b[0m \u001b[0mPIL\u001b[0m \u001b[1;32mimport\u001b[0m \u001b[0mImage\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mModuleNotFoundError\u001b[0m: No module named 'simplejson'" ] } ], "source": [ "from flask import Flask, request, Response\n", "import simplejson\n", "import tensorflow\n", "import visualization_utils as vis_util\n", "from PIL import Image\n", "import numpy as np\n", "from PIL import Image\n", "import numpy as np\n", "import label_map_util\n", "import tensorflow as tf\n", "%matplotlib inline\n", "from matplotlib import pyplot as plt\n", "import time\n", "import cv2\n", "from numpy import asarray\n", "\n", "# Creation of the Flask app\n", "app = Flask(__name__)\n", "# Flask route for Liveness checks\n", "\n", "\n", "@app.route(\"/isalive\")\n", "def isalive():\n", " print(\"/isalive request\")\n", " status_code = Response(status=200)\n", " return status_code\n", "\n", "\n", "# Flask route for predictions\n", "\n", "\n", "@app.route('/predict', methods=['GET', 'POST'])\n", "def prediction():\n", " total_time_start = time.time()\n", "\n", "\n", " def loadImageIntoNumpyArray(image):\n", " (im_width, im_height) = image.size\n", " if image.getdata().mode == \"RGBA\":\n", " image = image.convert('RGB')\n", " return asarray(image).reshape((im_height, im_width, 3)).astype(np.uint8)\n", "\n", " def main(image_path,model_path,model_PATH_TO_CKPT,path_to_labels):\n", " image = Image.open(image_path)\n", " image_np = loadImageIntoNumpyArray(image)\n", " image_np_expanded = np.expand_dims(image_np, axis=0)\n", " label_map = label_map_util.load_labelmap(path_to_labels)\n", " # print(\"label_map------->\",type(label_map))\n", " categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=100, use_display_name=True)\n", " category_index = label_map_util.create_category_index(categories)\n", " # print(\"category index-->\",category_index)\n", "\n", " detection_graph = tf.Graph()\n", " with detection_graph.as_default():\n", " od_graph_def = tf.compat.v1.GraphDef()\n", " with tf.compat.v2.io.gfile.GFile(model_PATH_TO_CKPT, 'rb') as fid:\n", " serialized_graph = fid.read()\n", " od_graph_def.ParseFromString(serialized_graph)\n", " tf.import_graph_def(od_graph_def, name='')\n", " sess = tf.compat.v1.Session(graph=detection_graph)\n", " # Input tensor is the image\n", " image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')\n", " # Output tensors are the detection boxes, scores, and classes\n", " # Each box represents a part of the image where a particular object was detected\n", " detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')\n", " # Each score represents level of confidence for each of the objects.\n", " # The score is shown on the result image, together with the class label.\n", " detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')\n", " detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')\n", " # Number of objects detected\n", " num_detections = detection_graph.get_tensor_by_name('num_detections:0')\n", " (boxes, scores, classes, num) = sess.run(\n", " [detection_boxes, detection_scores, detection_classes, num_detections],\n", " feed_dict={image_tensor: image_np_expanded})\n", " vis_util.visualize_boxes_and_labels_on_image_array(\n", " image_np,\n", " np.squeeze(boxes),\n", " np.squeeze(classes).astype(np.int32),\n", " np.squeeze(scores),\n", " category_index,\n", " use_normalized_coordinates=True,\n", " line_thickness=8,\n", " min_score_thresh=0.1)\n", " %matplotlib inline\n", " from matplotlib import pyplot as plt\n", " # print(\"boxes:\",boxes)\n", " # print(\"class:\",classes)\n", " objects = []\n", " threshold = 0.5\n", " # print(\"category:\",category_index)\n", " boxes = boxes[0]\n", " for index, value in enumerate(classes[0]):\n", " object_dict = {}\n", " if scores[0, index] > threshold:\n", " object_dict[\"class\"] = (category_index.get(value)).get('name')\n", " object_dict[\"score\"] = round(scores[0, index] * 100,2)\n", " box = tuple(boxes[index].tolist())\n", " ymin, xmin, ymax, xmax= box\n", " im_width,im_height = 360,360\n", " left, right, top, bottom = (xmin * im_width, xmax * im_width, \n", " ymin * im_height, ymax * im_height)\n", " object_dict[\"box\"] = (int(left), int(right), int(top), int(bottom))\n", " objects.append(object_dict)\n", "\n", " image_orignal = Image.open(image_path)\n", " image_np_orignal = loadImageIntoNumpyArray(image_orignal)\n", "\n", "\n", " fig, ax = plt.subplots(1,2)\n", "\n", " fig.suptitle('Tag Deciphering')\n", "\n", " ax[0].imshow(image_np_orignal,aspect='auto');\n", " ax[1].imshow(image_np,aspect='auto');\n", "\n", "\n", " return objects\n", "\n", " image_path = \"C://Users//thirdeye//Documents//ytag_gcp//test_images//33102340_20221005_1.JPG\"\n", " model_path = \"C://Users//thirdeye//Documents//ytag_gcp//ytag//yellow-black-28-may-22-inc-30-april-21\"\n", " model_PATH_TO_CKPT = model_path+\"//inference//frozen_inference_graph.pb\"\n", " path_to_labels = \"C://Users//thirdeye//Documents//ytag_gcp//ytag//tf_label_map.pbtxt\"\n", "\n", " result = main(image_path,model_path,model_PATH_TO_CKPT,path_to_labels)\n", " # print(\"result-\",result)\n", " # list_to_be_sorted= [{'class': 'Y', 'score': 99.97, 'box': (157, 191, 269, 288)}, {'class': '6', 'score': 99.93, 'box': (158, 191, 247, 267)}, {'class': '9', 'score': 99.88, 'box': (156, 190, 179, 196)}, {'class': '4', 'score': 99.8, 'box': (156, 189, 198, 219)}, {'class': '1', 'score': 99.65, 'box': (157, 189, 222, 244)}, {'class': 'F', 'score': 63.4, 'box': (155, 185, 157, 175)}]\n", " newlist = sorted(result, key=lambda k: k['box'][3],reverse=False)\n", "\n", " text =''\n", " for each in newlist:\n", " if(each['score']>65):\n", " text += each['class']\n", " # print(\"text:\",text)\n", " if(text!=\"\"):\n", " text = text.replace(\"yellowTag\", \"\") \n", " result = text\n", " else:\n", " result = \"No Vertical Tag Detected\"\n", " response = {\"predictions\": [result]}\n", " total_time_end = time.time()\n", " print(\"total time : \",round((total_time_end-total_time_start),2))\n", " return simplejson.dumps(response)\n", "\n", "\n", "if __name__ == \"__main__\":\n", " app.run(debug=True, host='0.0.0.0', port=8087)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64 bit (AMD64)]" }, "vscode": { "interpreter": { "hash": "c58a6b68d966fd9b37abe1a881a7bc4a5fe187b07fe812e6c998975c787534e1" } } }, "nbformat": 4, "nbformat_minor": 5 }