{"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\nfor 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":{"trusted":true},"cell_type":"code","source":"!unzip /kaggle/input/cassava-disease/train.zip\n!unzip /kaggle/input/cassava-disease/test.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# inflating: test/0/test-img-1311.jpg  \n# inflating: test/0/test-img-452.jpg  \n# inflating: test/0/test-img-3506.jpg  \n# inflating: test/0/test-img-2618.jpg ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# !pip install opencv-python==4.5.1.48","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2 as cv\n\nnet = cv.dnn_DetectionModel('../input/cassava-416-yolov4-weights/yolov4-holiday.cfg',\n                            '../input/cassava-416-yolov4-weights/yolov4-holiday_final.weights')\nnet.setInputSize(416, 416)\nnet.setInputScale(1.0 / 255)\nnet.setInputSwapRB(True)\n\nframe = cv.imread('./test/0/test-img-1311.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":"import cv2 as cv\nimport os\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)\nmy_dict = {}\ni = 0\n\n\nbasepath='./test/0'\nsubmission = pd.DataFrame(columns=['image_id','label'])\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) == 'tuple':\n#                             classes = np.asarray(classes)\n#                         elif type(confidences) == 'tuple':\n#                             confidences = np.asarray(confidences)\n                        if type(classes) is not tuple:\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                                \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        #                 print(\"Detected Class is {} with confidence {}\".format(names[classId], '%.2f' % confidence))\n                        else:\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 occured: \", 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.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Completed!\")","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}