File size: 9,690 Bytes
03a6cbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
{
 "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<module>\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
}