File size: 8,704 Bytes
b59c9b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Bo5_91rSgTg3"
   },
   "source": [
    "**Importing Libraries**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "id": "1FOULt5NeSny"
   },
   "outputs": [],
   "source": [
    "import shutil\n",
    "import os, sys, random\n",
    "from glob import glob\n",
    "import pandas as pd\n",
    "from shutil import copyfile\n",
    "import pandas as pd\n",
    "from sklearn import preprocessing, model_selection\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib import patches\n",
    "import numpy as np\n",
    "import os\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "mDgSjs4FMS82"
   },
   "source": [
    "Refer [this blog](https://towardsai.net/p/computer-vision/yolo-v5-object-detection-on-a-custom-dataset) for more information. Its an excellent resource.  \n",
    "\n",
    "**Cloning Official Repo**  \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3dyetdeOpUIR"
   },
   "outputs": [],
   "source": [
    "!git clone  'https://github.com/ultralytics/yolov5.git'\n",
    "!sed -i 's/PyYAML>=5.3.1/PyYAML==5.4.1/g' ./yolov5/requirements.txt\n",
    "!pip install -qr 'yolov5/requirements.txt'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "rOTf_JHIMV9T",
    "outputId": "514c1cfa-c1e0-4c87-a3a1-672eb744e2cd"
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'yolov5/tobacco_data.yaml'"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Setting the model parameters\n",
    "# copying the custom_dataset.yaml file to the project repo\n",
    "# setting number of classes to two (since the tobacco 800 dataset contains 2 classes, Logo & Signature)\n",
    "shutil.copyfile('Training/tobacco_data.yaml', 'yolov5/tobacco_data.yaml') "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "/Users/vivekgupta/DS/Signature/1. Detection\n"
     ]
    }
   ],
   "source": [
    "cd .."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {
     "base_uri": "https://localhost:8080/"
    },
    "id": "rOTf_JHIMV9T",
    "outputId": "514c1cfa-c1e0-4c87-a3a1-672eb744e2cd"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "train: tobacco_yolo_format/images/train\r\n",
      "val: tobacco_yolo_format/images/valid\r\n",
      "\r\n",
      "nc: 2\r\n",
      "names: ['DLLogo', 'DLSignature']\r\n"
     ]
    }
   ],
   "source": [
    "!cat yolov5/tobacco_data.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "Lfn8HpbaO3tD"
   },
   "source": [
    "**Setting some augmentations**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "id": "wvg-PdCOO26C"
   },
   "outputs": [],
   "source": [
    "# !sed -i 's/perspective: 0.0/perspective: 0.1/g' ./yolov5/data/hyp.finetune.yaml\n",
    "# !sed -i 's/shear: 0.0/shear: 0.1/g' ./yolov5/data/hyp.finetune.yaml\n",
    "# !sed -i 's/flipud: 0.0/flipud: 0.5/g' ./yolov5/data/hyp.finetune.yaml\n",
    "# !sed -i 's/degrees: 0.0/degrees: 0.2/g' ./yolov5/data/hyp.finetune.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xCtQwpQHPXnD"
   },
   "source": [
    "**Training**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "jgUydkkSp3gz"
   },
   "source": [
    "--img 640 is the width of the images.  \n",
    "`Dataset.yaml` file should be present in the directory pointed by --data.  \n",
    "--cfg models/model.yaml is used to set the model we want to train on. I have used yolov5x.yaml, more information could be found [here.](https://github.com/ultralytics/yolov5#pretrained-checkpoints)  \n",
    "  \n",
    "\n",
    "Many useful tips and information regarding training and testing could be foung [here](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results). **This will helps to clear a good amount of doubts and errors. Also I recommend you to go through the issues section of the repo if you faces any errors or doubts. Legand has it that you will find the solution for your miseries there.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "id": "NKvLEPfHOSQw",
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[34m\u001b[1mtrain: \u001b[0mweights=yolov5s.pt, cfg=yolov5/models/yolov5s.yaml, data=yolov5/tobacco_data.yaml, hyp=yolov5/data/hyps/hyp.scratch-low.yaml, epochs=100, batch_size=16, imgsz=640, rect=False, resume=False, nosave=False, noval=False, noautoanchor=False, noplots=False, evolve=None, bucket=, cache=None, image_weights=False, device=mp, multi_scale=False, single_cls=False, optimizer=SGD, sync_bn=False, workers=8, project=yolov5/runs/train, name=Tobacco-run, exist_ok=False, quad=False, cos_lr=False, label_smoothing=0.0, patience=100, freeze=[0], save_period=-1, seed=0, local_rank=-1, entity=None, upload_dataset=False, bbox_interval=-1, artifact_alias=latest\n",
      "\u001b[34m\u001b[1mgithub: \u001b[0mup to date with https://github.com/ultralytics/yolov5 ✅\n",
      "fatal: cannot change to '/Users/vivekgupta/DS/Signature/1.': No such file or directory\n",
      "Traceback (most recent call last):\n",
      "  File \"yolov5/train.py\", line 647, in <module>\n",
      "    main(opt)\n",
      "  File \"yolov5/train.py\", line 522, in main\n",
      "    device = select_device(opt.device, batch_size=opt.batch_size)\n",
      "  File \"/Users/vivekgupta/DS/Signature/1. Detection/yolov5/utils/torch_utils.py\", line 118, in select_device\n",
      "    assert torch.cuda.is_available() and torch.cuda.device_count() >= len(device.replace(',', '')), \\\n",
      "AssertionError: Invalid CUDA '--device mp' requested, use '--device cpu' or pass valid CUDA device(s)\n"
     ]
    }
   ],
   "source": [
    "!python yolov5/train.py --img 640 --batch 16 --epochs 100 --weights \"yolov5s.pt\" \\\n",
    "--data yolov5/tobacco_data.yaml --cfg yolov5/models/yolov5s.yaml --name Tobacco-run --device 'mp'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "xB2bMpZyrWS3"
   },
   "source": [
    "**Testing**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ly5RlSNsrZqr"
   },
   "source": [
    "**To predict images in a folder**  \n",
    "--hide-labels is used to hide the labels in the detected images.  \n",
    "--hide-conf is used to hide the confidence scores in the detected images.  --classes [0, 1, etc] used to detect only the classes mentioned here. For our use case we need only signature class, so use --classes 1.\n",
    "--line-thickness integer used to set the thickness of bounging box.  \n",
    "--save-crop and --save-txt used to save the crops and labels.  \n",
    "--project could be used to specify the results path  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "uBOJ9IPvPZ8h"
   },
   "outputs": [],
   "source": [
    "!python yolov5/detect.py --source TobaccoData_Raw/tobacco_yolo_format/images/valid/ --weights 'yolo_model/best.pt' \\\n",
    " --hide-labels --hide-conf --classes 1 --line-thickness 2 --device 'mps'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "n9PS6yTCs3td"
   },
   "source": [
    "**To predict a single image**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "kdRwxu7oY53A"
   },
   "outputs": [],
   "source": [
    "!python yolov5/detect.py --source tobacco_yolo_format/images/valid/imagename --weights 'runs/train/Tobacco-run/weights/best.pt' \\\n",
    " --hide-labels --hide-conf --classes 1 --line-thickness 2 "
   ]
  }
 ],
 "metadata": {
  "accelerator": "GPU",
  "colab": {
   "collapsed_sections": [],
   "name": "YOLOv5_Tobacco.ipynb",
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}