{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n#         print(os.path.join(dirname, filename))\n        pass","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-03-04T07:21:28.852266Z","iopub.execute_input":"2023-03-04T07:21:28.852702Z","iopub.status.idle":"2023-03-04T07:21:30.073683Z","shell.execute_reply.started":"2023-03-04T07:21:28.852665Z","shell.execute_reply":"2023-03-04T07:21:30.072551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd\nfrom tensorflow.keras.utils import load_img,img_to_array\nimport matplotlib.pyplot as plt\nimport matplotlib\nfrom pathlib import Path","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:30.596787Z","iopub.execute_input":"2023-03-04T07:21:30.597409Z","iopub.status.idle":"2023-03-04T07:21:30.602709Z","shell.execute_reply.started":"2023-03-04T07:21:30.597373Z","shell.execute_reply":"2023-03-04T07:21:30.601541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number OF Trainning Images:\"+ str(len(os.listdir(\"/kaggle/input/global-wheat-detection/train\"))))\nprint(\"Number OF Testing Images:\"+ str(len(os.listdir(\"/kaggle/input/global-wheat-detection/test\"))))","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:33.487146Z","iopub.execute_input":"2023-03-04T07:21:33.487523Z","iopub.status.idle":"2023-03-04T07:21:33.499177Z","shell.execute_reply.started":"2023-03-04T07:21:33.487492Z","shell.execute_reply":"2023-03-04T07:21:33.497596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df=pd.read_csv(r'/kaggle/input/global-wheat-detection/train.csv')","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:33.501640Z","iopub.execute_input":"2023-03-04T07:21:33.502499Z","iopub.status.idle":"2023-03-04T07:21:33.655267Z","shell.execute_reply.started":"2023-03-04T07:21:33.502462Z","shell.execute_reply":"2023-03-04T07:21:33.654064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x', 'y', 'width', 'hieght']):\n    df[column] = bboxs[:,i] \n      \ndf.drop(columns=['bbox'], inplace=True)\ndf['x_center'] = df['x'] + df['width']/2\ndf['y_center'] = df['y'] + df['hieght']/2\ndf['classes'] = 0\n\ndf['x_center'] = df['x_center']/1024\ndf['y_center'] = df['y_center']/1024\ndf['width'] = df['width']/1024\ndf['hieght'] = df['hieght']/1024\ndf = df[['image_id', 'width', 'hieght','x_center','y_center','classes']]\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:36.411118Z","iopub.execute_input":"2023-03-04T07:21:36.411639Z","iopub.status.idle":"2023-03-04T07:21:36.884366Z","shell.execute_reply.started":"2023-03-04T07:21:36.411582Z","shell.execute_reply":"2023-03-04T07:21:36.882879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm \nimport shutil as sh","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:36.886395Z","iopub.execute_input":"2023-03-04T07:21:36.887076Z","iopub.status.idle":"2023-03-04T07:21:36.892238Z","shell.execute_reply.started":"2023-03-04T07:21:36.887035Z","shell.execute_reply":"2023-03-04T07:21:36.890914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Path('/kaggle/working/Dataset/train/').mkdir(parents=True, exist_ok=True)\nPath('/kaggle/working/Dataset/val/').mkdir(parents=True, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:38.165486Z","iopub.execute_input":"2023-03-04T07:21:38.166466Z","iopub.status.idle":"2023-03-04T07:21:38.172372Z","shell.execute_reply.started":"2023-03-04T07:21:38.166424Z","shell.execute_reply":"2023-03-04T07:21:38.171128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:38.504128Z","iopub.execute_input":"2023-03-04T07:21:38.504532Z","iopub.status.idle":"2023-03-04T07:21:39.690355Z","shell.execute_reply.started":"2023-03-04T07:21:38.504497Z","shell.execute_reply":"2023-03-04T07:21:39.689061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"index = list(set(df.image_id))","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:40.044400Z","iopub.execute_input":"2023-03-04T07:21:40.044814Z","iopub.status.idle":"2023-03-04T07:21:40.065576Z","shell.execute_reply.started":"2023-03-04T07:21:40.044778Z","shell.execute_reply":"2023-03-04T07:21:40.064552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"source = 'train'\n\nif True:\n    for fold in [0]:\n        val_index = index[len(index)*fold//5:len(index)*(fold+1)//5]\n        for name,mini in tqdm(df.groupby('image_id')):\n            # print(f\"name: {name} ::mini {mini}\")\n            \n            if name in val_index:\n                path2save = '/kaggle/working/Dataset/val/'\n            else:\n                path2save = '/kaggle/working/Dataset/train/'\n\n            with open(path2save+name+\".txt\", 'w+') as f:\n                row = mini[['classes','x_center','y_center','width','hieght']].astype(float).values\n                row = row.astype(str)\n                for j in range(len(row)):\n                    text = ' '.join(row[j])\n                    f.write(text)\n                    f.write(\" \\n  \")\n            # if not os.path.exists('/kaggle/working/Data/images/{}'.format(path2save)):\n            #     os.makedirs('/kaggle/working/Data/images/{}'.format(path2save))\n            sh.copy(f\"/kaggle/input/global-wheat-detection/train/{name}.jpg\", f'{path2save}/{name}.jpg')","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:40.432218Z","iopub.execute_input":"2023-03-04T07:21:40.432574Z","iopub.status.idle":"2023-03-04T07:21:49.133671Z","shell.execute_reply.started":"2023-03-04T07:21:40.432543Z","shell.execute_reply":"2023-03-04T07:21:49.131915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install PyYAML","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:49.135842Z","iopub.execute_input":"2023-03-04T07:21:49.136222Z","iopub.status.idle":"2023-03-04T07:21:59.164642Z","shell.execute_reply.started":"2023-03-04T07:21:49.136183Z","shell.execute_reply":"2023-03-04T07:21:59.163368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import yaml\nwheet_yaml = dict(\n    train ='/kaggle/working/Dataset/train',\n    val ='/kaggle/working/Dataset/val',\n    nc =1,\n    names =[\"wheat\"]\n)\n\nwith open('wheet.yaml', 'w') as outfile:\n    yaml.dump(wheet_yaml, outfile, default_flow_style=True)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:59.170025Z","iopub.execute_input":"2023-03-04T07:21:59.170393Z","iopub.status.idle":"2023-03-04T07:21:59.182559Z","shell.execute_reply.started":"2023-03-04T07:21:59.170355Z","shell.execute_reply":"2023-03-04T07:21:59.181442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:21:59.188406Z","iopub.execute_input":"2023-03-04T07:21:59.191309Z","iopub.status.idle":"2023-03-04T07:22:00.370510Z","shell.execute_reply.started":"2023-03-04T07:21:59.191273Z","shell.execute_reply":"2023-03-04T07:22:00.369220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !ls /kaggle/working/Dataset/val","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:22:03.488142Z","iopub.execute_input":"2023-03-04T07:22:03.488792Z","iopub.status.idle":"2023-03-04T07:22:03.494045Z","shell.execute_reply.started":"2023-03-04T07:22:03.488750Z","shell.execute_reply":"2023-03-04T07:22:03.492949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install ultralytics","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:22:04.564846Z","iopub.execute_input":"2023-03-04T07:22:04.565760Z","iopub.status.idle":"2023-03-04T07:22:14.636130Z","shell.execute_reply.started":"2023-03-04T07:22:04.565724Z","shell.execute_reply":"2023-03-04T07:22:14.634886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import ultralytics\nfrom ultralytics import YOLO\nultralytics.checks()\n\nfrom ultralytics import YOLO\n\n# Load a model\nmodel = YOLO(\"yolov8n.yaml\")  # build a new model from scratch\nmodel = YOLO(\"yolov8n.pt\")  # load a pretrained model (recommended for training)\n\n# Use the model\nmodel.train(data=\"/kaggle/working/wheet.yaml\", epochs=100)  # train the model\nmetrics = model.val()  # evaluate model performance on the validation set\n# # results = model(\"https://ultralytics.com/images/bus.jpg\")  # predict on an image\nsuccess = model.export(format=\"onnx\")  # export the model to ONNX format\n","metadata":{"execution":{"iopub.status.busy":"2023-03-04T07:22:17.305644Z","iopub.execute_input":"2023-03-04T07:22:17.306048Z","iopub.status.idle":"2023-03-04T08:37:43.402045Z","shell.execute_reply.started":"2023-03-04T07:22:17.306010Z","shell.execute_reply":"2023-03-04T08:37:43.399950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/working/runs/detect/train4/weights/","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:40:51.990960Z","iopub.execute_input":"2023-03-04T08:40:51.991723Z","iopub.status.idle":"2023-03-04T08:40:53.016266Z","shell.execute_reply.started":"2023-03-04T08:40:51.991683Z","shell.execute_reply":"2023-03-04T08:40:53.015024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!yolo detect predict model=/kaggle/working/runs/detect/train4/weights/best.pt source=\"/kaggle/input/global-wheat-detection/test/2fd875eaa.jpg\"  # predict with custom model","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:41:38.164094Z","iopub.execute_input":"2023-03-04T08:41:38.164582Z","iopub.status.idle":"2023-03-04T08:41:49.200325Z","shell.execute_reply.started":"2023-03-04T08:41:38.164539Z","shell.execute_reply":"2023-03-04T08:41:49.199073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls /kaggle/working/runs/","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:42:43.931004Z","iopub.execute_input":"2023-03-04T08:42:43.931612Z","iopub.status.idle":"2023-03-04T08:42:44.955265Z","shell.execute_reply.started":"2023-03-04T08:42:43.931571Z","shell.execute_reply":"2023-03-04T08:42:44.953893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!yolo detect predict model=/kaggle/working/runs/detect/train4/weights/best.pt source=\"/kaggle/input/global-wheat-detection/test\"  # predict with custom model","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:42:24.707202Z","iopub.execute_input":"2023-03-04T08:42:24.707610Z","iopub.status.idle":"2023-03-04T08:42:36.103074Z","shell.execute_reply.started":"2023-03-04T08:42:24.707573Z","shell.execute_reply":"2023-03-04T08:42:36.101795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Prediction","metadata":{}},{"cell_type":"code","source":"!ls /kaggle/working/","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:47:51.399516Z","iopub.execute_input":"2023-03-04T08:47:51.400069Z","iopub.status.idle":"2023-03-04T08:47:53.063501Z","shell.execute_reply.started":"2023-03-04T08:47:51.400001Z","shell.execute_reply":"2023-03-04T08:47:53.062252Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Path('/kaggle/working/predicted_output/').mkdir(parents=True, exist_ok=True)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T08:49:25.603066Z","iopub.execute_input":"2023-03-04T08:49:25.603542Z","iopub.status.idle":"2023-03-04T08:49:25.610975Z","shell.execute_reply.started":"2023-03-04T08:49:25.603500Z","shell.execute_reply":"2023-03-04T08:49:25.609977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nfrom ultralytics import YOLO\nimport cv2\n\nmodel_path = os.path.join('/kaggle/working/', 'runs', 'detect', 'train4', 'weights', 'best.pt')\nprint(model_path)\n# Load a model\nmodel = YOLO(model_path)  # load a custom model\nfor img in os.listdir('/kaggle/input/global-wheat-detection/test/'):\n    print(img.split('.')[0])\n    img_path = os.path.join('/kaggle/input/global-wheat-detection/test/', img)\n#     print(img_path)\n    res = model(img_path)\n    res_plotted = res[0].plot()\n#     cv2.imshow(\"result\", res_plotted)\n    cv2.imwrite('/kaggle/working/predicted_output/{}_op.png'.format(img.split('.')[0]),res_plotted)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T09:10:02.406908Z","iopub.execute_input":"2023-03-04T09:10:02.408004Z","iopub.status.idle":"2023-03-04T09:10:03.968980Z","shell.execute_reply.started":"2023-03-04T09:10:02.407961Z","shell.execute_reply":"2023-03-04T09:10:03.967784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}