{"cells":[{"metadata":{},"cell_type":"markdown","source":"This notebook is for submisssion of model trained using Tensorflow object detection API with InceptionV2.\n\n\nTraining Code is in [Github](https://github.com/DhruvMakwana/Global-Wheat-Detection).check it out:)","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport tensorflow as tf\nimport cv2 \nimport matplotlib.pyplot as plt\nimport os\nimport pandas as pd\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_path = '../input/global-wheat-tf-object-detection-api-inception-v2/inceptinV2_frozen_inference_graph.pb'\ntest_images_path = '../input/global-wheat-detection/test/'\nsample_csv = '../input/global-wheat-detection/sample_submission.csv'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv(sample_csv)\nsub.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Detecting from test images","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with tf.compat.v1.gfile.FastGFile(model_path, 'rb') as f:\n    graph_def = tf.compat.v1.GraphDef()\n    graph_def.ParseFromString(f.read())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.DataFrame(columns=list(sub.columns))\nplt.figure(figsize=(20,10))\n\nwith tf.compat.v1.Session() as sess:\n        # Restore session\n        sess.graph.as_default()\n        tf.import_graph_def(graph_def, name='')\n\n        for ind,image_name in tqdm(enumerate(os.listdir(test_images_path))) :\n\n            img_name = image_name\n\n    \n\n\n            # Read and preprocess an image.\n            img = cv2.imread(test_images_path + img_name,1)\n            rows = img.shape[0]\n            cols = img.shape[1]\n            inp = cv2.resize(img, (1024, 1024))\n            inp = inp[:, :, [2, 1, 0]]  # BGR2RGB\n\n            # Run the model\n            out = sess.run([sess.graph.get_tensor_by_name('num_detections:0'),\n                            sess.graph.get_tensor_by_name('detection_scores:0'),\n                            sess.graph.get_tensor_by_name('detection_boxes:0'),\n                            sess.graph.get_tensor_by_name('detection_classes:0')],\n                            feed_dict={'image_tensor:0': inp.reshape(1, inp.shape[0], inp.shape[1], 3)})\n\n            # Saving detected bounding boxes.\n            num_detections = int(out[0][0])\n            pred_str = ''\n            for i in range(num_detections):\n                classId = int(out[3][0][i])\n                score = float(out[1][0][i])\n                bbox = [float(v) for v in out[2][0][i]]\n                if score > 0.3:\n                    x = int(bbox[1] * cols)\n                    y = int(bbox[0] * rows)\n                    xmax = int(bbox[3] * cols)\n                    ymax = int(bbox[2] * rows)\n\n                    cv2.rectangle(img, (x, y), (xmax, ymax), (0,0,255), 2)\n\n                    pred = '{} {} {} {} {} '.format(np.round(score,2),x,y,xmax-x,ymax-y)\n                    pred_str = pred_str + pred\n            if ind<10:\n                plt.subplot(2,5,ind+1)\n                plt.imshow(cv2.cvtColor(img,cv2.COLOR_BGR2RGB))\n                plt.title(image_name[:-4])\n                plt.axis('off')\n\n            submission.loc[ind,'image_id'] = image_name[:-4]\n            submission.loc[ind,'PredictionString'] = pred_str\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Creating submission file","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}