Run yolov5 on CPU (detailed steps + suitable for getting started)

Table of contents

1. Create a new environment

2. Import the Pytorch library

3. New projects

4. Test

5. Prepare the dataset

Six, modify the configuration file

7. Training

Eight, example test

9. Conclusion


By default, everyone has Anaconda and Pycharm installed, and knows the basic operations

1. Create a new environment

Open the cmd window, enter conda create -n yolov5 python=3.7, press Enter

Wait for a while, enter y, press Enter

After a while, done appears, indicating that the new environment was created successfully!

You can choose the name at will, but it is recommended to choose the same name as me. It is recommended that all subsequent operations be consistent with me, so that everyone can get started for the first time; the Python interpreter version should choose 3.7, because I have encountered unknown problems before choosing 3.10

2. Import the Pytorch library

My computer is a Thinkbook14p of R7-5800H, there is no independent display, so I use the CPU version of PyTorch

First, enter conda activate yolov5 in the cmd window, press Enter, and activate the new environment you just created

If (yolov5) appears before the path, the activation is successful!

Then enter PyTorch official website PyTorch , select the following configuration:

Copy the last line of code to the cmd window and press Enter

Wait for a while, enter y, press Enter; wait for a while, done appears, indicating that the Pytorch library was imported successfully!

3. New projects

First download the yolov5 installation package mirrors/ultralytics/yolov5 GitCode from this website

After the download is complete, unzip it, right-click the unzipped folder, and select Open as Pycharm Project

The opened Pycharm interface looks like this:

Click <No Interpreter> in the lower right corner and select Add Interpreter

Click the Conda environment on the left side of the pop-up interface, click the existing environment, select the python executable file in the new environment created before, and click OK

You can see that the lower right corner of the Pycharm interface has become Python3.7 (yolov5)

4. Test

Open the requirements.txt file, which contains various packages required for yolov5 to run. Copy the first line of the command to run in the terminal

This process can be fast or slow, depending on the speed of the network, wait quietly~ There may be problems with the installation of several packages, it doesn't matter, you can find the solution by searching the error information on CSDN!

After everything is installed, run the detect.py file on the left

If there is no error after the operation, and the following two processed pictures appear in the runs\detect\exp directory on the left, it means that there is no problem with the previous operations, congratulations! Preparations are over

5. Prepare the dataset

Please follow my method to create the following empty folders under the yolov5-master path to facilitate subsequent management

I downloaded the training data cat and dog recognition data set provided by the blogger in this article Zhihu - Zhihu , there are 25000 pictures after decompression, obviously it is impossible to use all of them. I selected the first 121 cat pictures and copied them to the yolov5-master\own_datas\images\train folder as the training set

Then enter pip install pyqt5 labelme in the Pycharm terminal and press Enter. These two libraries are used to label datasets

After the installation is complete, enter labelme in the terminal and press Enter

A window will pop up, and the training set will be marked in this window.

Click Open Dir in the upper left corner, select the yolov5-master\own_datas\images\train folder, and the images in the training set will appear. Right-click and select Create Rectangle to frame the cat in the picture

After the box selection is complete, enter the tag name cat, click ok, and the tag will be saved. If there are multiple cats, continue to select

After the entire picture frame is selected, click Next Image on the left, and save the label file to the path yolov5-master\own_datas\labels\json according to the prompt. The format of the file is .json

After about half an hour...

After all the pictures are marked, you can see 121 .json files corresponding to the same number of pictures in the training set in the yolov5-master\own_datas\labels\json folder

It's not over yet, because yolov5 can only recognize tags in .txt format, and you need to convert the .json file into a .txt file

Create a new json2txt.py file in the yolov5-master folder

Copy the following code into it:

import json
import os

name2id = {'cat': 0}  # 标签名称


def convert(img_size, box):
    dw = 1. / (img_size[0])
    dh = 1. / (img_size[1])
    x = (box[0] + box[2]) / 2.0 - 1
    y = (box[1] + box[3]) / 2.0 - 1
    w = box[2] - box[0]
    h = box[3] - box[1]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def decode_json(json_floder_path, json_name):
    txt_name = 'C:/Users/xieji/Downloads/yolov5-master/own_datas/labels/txt/' + json_name[0:-5] + '.txt'
    # txt文件夹的绝对路径
    txt_file = open(txt_name, 'w')

    json_path = os.path.join(json_floder_path, json_name)
    data = json.load(open(json_path, 'r', encoding='gb2312', errors='ignore'))

    img_w = data['imageWidth']
    img_h = data['imageHeight']

    for i in data['shapes']:

        label_name = i['label']
        if (i['shape_type'] == 'rectangle'):
            x1 = int(i['points'][0][0])
            y1 = int(i['points'][0][1])
            x2 = int(i['points'][1][0])
            y2 = int(i['points'][1][1])

            bb = (x1, y1, x2, y2)
            bbox = convert((img_w, img_h), bb)
            txt_file.write(str(name2id[label_name]) + " " + " ".join([str(a) for a in bbox]) + '\n')


if __name__ == "__main__":

    json_floder_path = 'C:/Users/xieji/Downloads/yolov5-master/own_datas/labels/json/'
    # json文件夹的绝对路径
    json_names = os.listdir(json_floder_path)
    for json_name in json_names:
        decode_json(json_floder_path, json_name)

The three commented places are where adjustments may need to be made. If everyone followed me exactly the same way, just replace C:/Users/xieji/Downloads/ with your own path.

Run json2txt.py, you can see the corresponding 121 .txt files in the yolov5-master\own_datas\labels\txt folder after the end

The last step is to copy all the files in the txt folder to the yolov5-master\own_datas\labels\train folder. Don't forget this step! Otherwise, an error will be reported during training and the label cannot be found.

Six, modify the configuration file

First copy the two files

Find the coco128.yaml file in the yolov5-master\data path, copy it to the yolov5-master\own_datas path, and rename it to cat.yaml

Because we are not using the coco128 dataset, but our own cat dataset. In fact, it is okay to not change it, but to change it to make it easier to understand

Find the yolov5s.yaml file in the yolov5-master\models path and copy it to the yolov5-master\own_datas path as well. I chose yolov5s because, although it is not very effective, it is faster. I have used yolov5l before, and I have to run all night...

Open the cat.yaml file, the first thing you need to modify are these three lines:

# path: ../datasets/coco128  # dataset root dir
train: own_datas/images/train  # train images (relative to 'path') 128 images
val: own_datas/images/train  # val images (relative to 'path') 128 images

Comment out the first line

The relative paths of the second and third lines, if they follow me exactly the same way, just follow me

Then modify these two lines:

nc: 1  # number of classes
names: ['cat']  # class names

nc is the number of categories and names is the category names. If you follow me exactly the same way, just follow me

Finally comment out this line because we don't use the coco128 dataset. It's okay to not comment, it doesn't matter, it's just that I'm obsessive-compulsive disorder

# download: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128.zip

Open the yolov5s.yaml file and need to modify this line:

nc: 1  # number of classes

7. Training

Open the train.py file

First modify the default of these lines:

    parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
    parser.add_argument('--cfg', type=str, default='own_datas/yolov5s.yaml', help='model.yaml path')
    parser.add_argument('--data', type=str, default='own_datas/cat.yaml', help='dataset.yaml path')

If you follow me exactly the same way, just follow me

Then modify the default of this line:

    parser.add_argument('--epochs', type=int, default=150)

The default value is 300, but the training time will be longer, I changed it to 150 here

The last thing to modify is the default of this line:

parser.add_argument('--workers', type=int, default=0, help='maximum number of dataloader workers')

I used the default value of 8 at the beginning, because my CPU has 8 cores and 16 threads. I saw elsewhere that if this value is set to the number of CPU cores of my computer, the training speed is the fastest, but an error is reported during training. Probably means that the memory burst, and then I changed it to 0

OK, start training!

Run train.py and wait...the fan will whirring non-stop...

I trained for 3 hours... Using the CPU is really slow... After the last epoch, [email protected] stopped at 0.995, [email protected]:0.95 stopped at 0.904, very good

You can view training-related information in the yolov5-master\runs\train\exp folder

The best.pt file in the weights folder is the trained model, which will be used later in the test

Eight, example test

It took three hours to train the model, let's see how it works!

I used the cat video I took for the test. You can use it yourself, as well as the photos (in fact, you can directly use the data set downloaded before, more than 20,000 photos can be used casually)

Put the test files in the yolov5-master\own_datas\images\test folder

Open the detect.py file

Modify the default of the following two lines:

    parser.add_argument('--weights', nargs='+', type=str, default='runs/train/exp/weights/best.pt', help='model path(s)')
    parser.add_argument('--source', type=str, default='own_datas/images/test', help='file/dir/URL/glob, 0 for webcam')

The first default is the relative path of the trained model file mentioned earlier

The second default is the relative path of the folder where the test files are stored

If you follow me exactly the same way, just follow me

Run detect.py, wait a while...

After the end, you can view the results in the yolov5-master\runs\detect\exp2 folder

I can't upload the video directly, I took a few pictures from the video to show you:

The effect is okay, not satisfactory, after all, only more than 100 pictures have been trained, and the relatively poor yolov5s network is used.

9. Conclusion

I am a novice myself, just getting into deep learning, I have been working on this project for several days, and I have gained a lot of knowledge.

After writing the draft, I deleted everything I had done before, and then ran it again according to the steps I wrote. It was smooth and no problem!

According to my process, it can be completed in one day (if there is a better independent display, it will be faster to run with GPU)

If you encounter a problem, just search on CSDN, and then combine your own wisdom, I believe it can be solved!

Mainly refer to this blog, thank you!

[Yolov5] 1. Seriously summarize the 6000-word Yolov5 nanny-level tutorial, 80-year-old grandma can understand it

Guess you like

Origin blog.csdn.net/weixin_54721509/article/details/122983561