{"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":"# 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-10-12T14:53:40.993360Z","iopub.execute_input":"2023-10-12T14:53:40.993610Z","iopub.status.idle":"2023-10-12T14:53:41.305991Z","shell.execute_reply.started":"2023-10-12T14:53:40.993587Z","shell.execute_reply":"2023-10-12T14:53:41.305073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\nimport shutil\n\n#将数据转换成yolo能够接受的模式\ndef data_to_yolo(path):\n    df = pd.read_csv(path)\n    bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))\n    for i, column in enumerate(['x', 'y', 'w', 'h']):\n        df[column] = bboxs[:, i]\n    df.drop(columns=['bbox'], inplace=True)\n    df['x_center'] = df['x'] + df['w'] / 2\n    df['y_center'] = df['y'] + df['h'] / 2\n    df['classes'] = 0\n    return df[['image_id', 'x', 'y', 'w', 'h', 'x_center', 'y_center', 'classes']]\n\nif __name__ == '__main__':\n\n    train_csv_path = '/kaggle/input/global-wheat-detection/train.csv' # 训练表格文件所在路径\n    new_dataframe = data_to_yolo(train_csv_path)\n    print(new_dataframe.head())\n    \n    index = list(set(new_dataframe.image_id))\n    \n    source = 'train'\n    if 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(new_dataframe.groupby('image_id')):\n                if name in val_index:\n                    path2save = 'val/'\n                else:\n                    path2save = 'train/'\n                if not os.path.exists('/kaggle/working/convertor/{}/labels'.format(path2save)):\n                    os.makedirs('/kaggle/working/convertor/{}/labels'.format(path2save))\n                with open('/kaggle/working/convertor/{}/labels/'.format(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('/kaggle/working/convertor/{}/images'.format(path2save)):\n                    os.makedirs('/kaggle/working/convertor/{}/images'.format(path2save))\n                shutil.copy(\"/kaggle/input/global-wheat-detection/{}/{}.jpg\".format(source, name),\n                            '/kaggle/working/convertor/{}/images/{}.jpg'.format(path2save, name))\n    \n    print('Convert Data to Yolo Finished')","metadata":{"execution":{"iopub.status.busy":"2023-10-12T14:53:46.859626Z","iopub.execute_input":"2023-10-12T14:53:46.860541Z","iopub.status.idle":"2023-10-12T14:54:21.613490Z","shell.execute_reply.started":"2023-10-12T14:53:46.860513Z","shell.execute_reply":"2023-10-12T14:54:21.612601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if os.path.exists('/kaggle/working/yolov5-master'):\n    !rm -r /kaggle/working/yolov5-master\n\n#input的文件只读，不可修改，将其复制到output\n!cp -r /kaggle/input/yolov5-master/yolov5-master /kaggle/working/yolov5-master","metadata":{"execution":{"iopub.status.busy":"2023-10-12T14:54:32.813342Z","iopub.execute_input":"2023-10-12T14:54:32.813958Z","iopub.status.idle":"2023-10-12T14:54:34.406735Z","shell.execute_reply.started":"2023-10-12T14:54:32.813928Z","shell.execute_reply":"2023-10-12T14:54:34.405500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!mkdir -p /root/.config/Ultralytics/\n!cp -r /kaggle/input/yolov5-master/yolov5-master/Arial.ttf /root/.config/Ultralytics/Arial.ttf","metadata":{"execution":{"iopub.status.busy":"2023-10-12T14:55:06.226500Z","iopub.execute_input":"2023-10-12T14:55:06.227565Z","iopub.status.idle":"2023-10-12T14:55:08.111761Z","shell.execute_reply.started":"2023-10-12T14:55:06.227520Z","shell.execute_reply":"2023-10-12T14:55:08.110508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install /kaggle/input/ultralytics/thop-0.1.1.post2209072238-py3-none-any.whl\n!pip install /kaggle/input/ultralytics/ultralytics-8.0.196-py3-none-any.whl","metadata":{"execution":{"iopub.status.busy":"2023-10-12T14:55:12.655983Z","iopub.execute_input":"2023-10-12T14:55:12.657170Z","iopub.status.idle":"2023-10-12T14:56:19.606470Z","shell.execute_reply.started":"2023-10-12T14:55:12.657125Z","shell.execute_reply":"2023-10-12T14:56:19.605333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#配置训练文件\n!python /kaggle/working/yolov5-master/train.py --weight /kaggle/working/yolov5-master/yolov5s.pt --cfg /kaggle/working/yolov5-master/models/yolov5s.yaml --epochs 1 --data /kaggle/working/yolov5-master/models/data.yaml --batch-size 16","metadata":{"execution":{"iopub.status.busy":"2023-10-12T07:38:53.753756Z","iopub.execute_input":"2023-10-12T07:38:53.754157Z","iopub.status.idle":"2023-10-12T07:39:53.257297Z","shell.execute_reply.started":"2023-10-12T07:38:53.754126Z","shell.execute_reply":"2023-10-12T07:39:53.256154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!python /kaggle/working/yolov5-master/detect.py --weights /kaggle/working/yolov5-master/runs/train/exp/weights/best.pt --img-size 640 --conf 0.8 --source /kaggle/input/global-wheat-detection/test --save-csv --project /kaggle/working --name prediction\n#!python /kaggle/working/yolov5-master/detect.py --weights /kaggle/input/bestalast-pt/best.pt --img-size 640 --conf 0.8 --source /kaggle/input/global-wheat-detection/test --save-csv --project /kaggle/working --name prediction\n\n!mv /kaggle/working/prediction/prediction.csv /kaggle/working/prediction/submission.csv\n\n!cp -r /kaggle/working/prediction/submission.csv /kaggle/working/submission.csv","metadata":{"execution":{"iopub.status.busy":"2023-10-11T14:49:52.646946Z","iopub.execute_input":"2023-10-11T14:49:52.647304Z","iopub.status.idle":"2023-10-11T14:50:03.371415Z","shell.execute_reply.started":"2023-10-11T14:49:52.647274Z","shell.execute_reply":"2023-10-11T14:50:03.370178Z"},"trusted":true},"execution_count":null,"outputs":[]}]}