{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n# for dirname, _, filenames in os.walk('/kaggle/input'):\n#     for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Inference with OpenCV**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import cv2 as cv\n\nnet = cv.dnn_DetectionModel('../input/cassava-leaf-disease-yolov4-model/yolov4-cassava.cfg',\n                            '../input/cassava-leaf-disease-yolov4-model/yolov4-cassava_final.weights')\nnet.setInputSize(512, 512)\nnet.setInputScale(1.0 / 255)\nnet.setInputSwapRB(True)\n\nframe = cv.imread('/kaggle/input/cassava-leaf-disease-classification/test_images/2216849948.jpg')\n\nwith open('../input/cassava-leaf-disease-yolov4-model/cassava.names', 'rt') as f:\n    names = f.read().rstrip('\\n').split('\\n')\n\nclasses, confidences, boxes = net.detect(frame, confThreshold=0.25, nmsThreshold=0.4)\nfor classId, confidence, box in zip(classes.flatten(), confidences.flatten(), boxes):\n    label = '%.2f' % confidence\n    label = '%s: %s' % (names[classId], label)\n    labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n    left, top, width, height = box\n    top = max(top, labelSize[1])\n    cv.rectangle(frame, box, color=(0, 255, 0), thickness=3)\n    cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)\n    cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\nprint(\"Detected Class is {} with confidence {}\".format(names[classId], '%.2f' % confidence))\ncv.imwrite('sample_detection.jpg', frame)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimg = cv.imread('sample_detection.jpg')\nprint(\"++++ Sample Output Image with detection ++++\")\nplt.imshow(img, aspect='auto')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"basepath='/kaggle/input/cassava-leaf-disease-classification/test_images'\nsubmission = pd.DataFrame(columns=['image_id','label'])\nmy_dict = {}\ni = 0\n\ntry:\n    with os.scandir(basepath) as entries:\n            for entry in entries:\n                if entry.is_file():\n                    if entry.name.lower().endswith('.jpg'):\n                        frame=cv.imread(basepath+'/'+entry.name)\n\n                        with open('../input/cassava-leaf-disease-yolov4-model/cassava.names', 'rt') as f:\n                            names = f.read().rstrip('\\n').split('\\n')\n\n                        classes, confidences, boxes = net.detect(frame, confThreshold=0.25, nmsThreshold=0.4)\n                        if type(classes) is not tuple:                           \n\n                            for classId, confidence, box in zip(classes.flatten(), confidences.flatten(), boxes):\n                                label = '%.2f' % confidence\n                                label = '%s: %s' % (names[classId], label)\n                                labelSize, baseLine = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, 0.5, 1)\n                                left, top, width, height = box\n                                top = max(top, labelSize[1])\n                                cv.rectangle(frame, box, color=(0, 255, 0), thickness=3)\n                                cv.rectangle(frame, (left, top - labelSize[1]), (left + labelSize[0], top + baseLine), (255, 255, 255), cv.FILLED)\n                                cv.putText(frame, label, (left, top), cv.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))\n            #                 print(\"Detected Class is {} with confidence {}\".format(names[classId], '%.2f' % confidence))\n                            #efficient way to append data in df\n                            data = [{'image_id': entry.name, 'label': names[classId]}]\n                            for entry in data:\n                                my_dict[i] = {\"image_id\": entry['image_id'], \"label\": entry['label']}\n                                i = i + 1\n                            submission = pd.DataFrame.from_dict(my_dict, \"index\")\n                        else:\n                            # to solve empty tuple error\n                            data = [{'image_id': entry.name, 'label': 3}]\n                            for entry in data:\n                                my_dict[i] = {\"image_id\": entry['image_id'], \"label\": entry['label']}\n                                i = i + 1\n                            submission = pd.DataFrame.from_dict(my_dict, \"index\")\nexcept Exception as exc:\n    print(\"Following error occurred: \", exc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission['label'] = submission['label'].astype('int64')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = submission.reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","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}