{"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 5GB 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":"# Importing Library","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import PIL.Image as Image\nimport cv2\nfrom IPython.display import display\nfrom sklearn.model_selection import train_test_split\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport pandas as pd\n\n%matplotlib inline\nnp.random.seed(42)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv('../input/global-wheat-detection/train.csv')\ndf_train_img = '../input/global-wheat-detection/train'\ndf_test_img = '../input/global-wheat-detection/test'\nsubmission = pd.read_csv('../input/global-wheat-detection/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Visualization","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_img = '../input/global-wheat-detection/train/005b0d8bb.jpg'\nfrom IPython.display import Image, display\ndisplay(Image(sample_img,width=300, height=300))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#helper fuction to show images\ndef show_images(image_ids):\n    \n    col = 5\n    row = min(len(image_ids) // col, 5)\n    \n    fig, ax = plt.subplots(row, col, figsize=(16, 8))\n    ax = ax.flatten()\n\n    for i, image_id in enumerate(image_ids):\n        image = cv2.imread('../input/global-wheat-detection/train' + '/{}.jpg'.format(image_id))\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n        ax[i].set_axis_off()\n        ax[i].imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(df_train.sample(n=15)['image_id'].values)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Implementing YOLO v5 model","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"YOLO v5 requires the dataset to be in the darknet format. Here’s an outline of what it looks like:\n\n* One txt with labels file per image\n* One row per object\n* Each row contains: class_index bbox_x_center bbox_y_center bbox_width bbox_height\n* Box coordinates must be normalized between 0 and 1\n\nWe need two configuration files. One for the dataset and one for the model we’re going to use. I have included those file in my input as yolo-data file\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#cloning yolov5 model\n!git clone https://github.com/ultralytics/yolov5\n\n#cloning NVIDIA/apex to speed up the process\n!git clone https://github.com/NVIDIA/apex.git","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!mv yolov5/* ./","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -r requirements.txt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Creating class_index bbox_x_center bbox_y_center bbox_width bbox_height\nbboxs = np.stack(df_train['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\nfor i, column in enumerate(['x', 'y', 'w', 'h']):\n    df_train[column] = bboxs[:,i]\ndf_train.drop(columns=['bbox'], inplace=True)\ndf_train['x_center'] = df_train['x'] + df_train['w']/2\ndf_train['y_center'] = df_train['y'] + df_train['h']/2\ndf_train['classes'] = 0\nfrom tqdm.auto import tqdm\nimport shutil as sh\ndf_train = df_train[['image_id','x', 'y', 'w', 'h','x_center','y_center','classes']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Extracting index from train data\nindex = list(set(df_train.image_id))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating dataset by divind the train data into train and val\nsource = 'train'\nif True:\n    for fold in [2]:\n        val_index = index[len(index)*fold//5:len(index)*(fold+1)//5]\n        for name,mini in tqdm(df_train.groupby('image_id')):\n            if name in val_index:\n                path2save = 'val2017/'\n            else:\n                path2save = 'train2017/'\n            if not os.path.exists('convertor/fold{}/labels/'.format(fold)+path2save):\n                os.makedirs('convertor/fold{}/labels/'.format(fold)+path2save)\n            with open('convertor/fold{}/labels/'.format(fold)+path2save+name+\".txt\", 'w+') as f:\n                row = mini[['classes','x_center','y_center','w','h']].astype(float).values\n                row = row/1024\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('convertor/fold{}/images/{}'.format(fold,path2save)):\n                os.makedirs('convertor/fold{}/images/{}'.format(fold,path2save))\n            sh.copy(\"../input/global-wheat-detection/{}/{}.jpg\".format(source,name),'convertor/fold{}/images/{}/{}.jpg'.format(fold,path2save,name))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Fit the Model\n!python train.py --img 1024 --batch 2 --epochs 1 \\\n  --data ../input/yolo-data/wheat.yaml --cfg ../input/yolo-data/yolov5x.yaml --weights yolov5x.pt \\\n  --name yolov5x_fold2 --cache","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#taking test images as inference images\n!find convertor/fold2/images/val2017 -maxdepth 1 -type f | head -50 | xargs cp -t \"./inference/images/\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#yolov5 in inference images\n!python detect.py --weights weights/last_yolov5x_fold2.pt \\\n  --img 1024 --conf 0.4 --source ./inference/images/","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize Result","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_img = 'inference/output/78edb3987.jpg'\nfrom IPython.display import Image, display\ndisplay(Image(sample_img,width=500, height=500))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# If you like my kernel...Please upvote...","execution_count":null}],"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}