How to use YOLO
- Make image dataset using roboflow
- Download dataset as
YOLOv8format - Install
ultralytics,cuda, andpytorchconda create -n yolo python=3.8 -y conda activate yolo conda install pytorch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 pytorch-cuda=11.7 -c pytorch -c nvidia -y pip install ultralytics
- Train
You can refer ultralytics/train documentation.
from ultralytics import YOLO model = YOLO("yolo11n.pt") results = model.train(data="/the/directory/of/data.yaml", epochs=100, imgsz=640)
model = YOLO("yolo.pt")
results = model.val(data="data.yaml")
metrics = {
"mAP50": results.box.map50,
"mAP50-95": results.box.map,
"Precision": results.box.mp,
"Recall": results.box.mr,
"AP_per_class": results.box.maps
}
print(f"mAP@0.5: {metrics['mAP50']:.4f}")
print(f"mAP@0.5:0.95: {metrics['mAP50-95']:.4f}")
print(f"Precision: {metrics['Precision']:.4f}")
print(f"Recall: {metrics['Recall']:.4f}")
print("AP per class:", metrics["AP_per_class"])- Is uses
valdata indata.yaml. (Then when istestdata used?) valdata is also used when training is finished.
The method val doesn't calculate IoU. So you have to make code to calculate IoU.
from ultralytics import YOLO
# Load a model
model = YOLO("best.pt") # pretrained model
# Run batched inference on a list of images
results = model('foldername/or/filename/of/video/or/image', stream=False) # return a generator of Results objects
# Process results generator
i = 0
for result in results:
result.show() # display to screen
result.save(filename=f"result/result{i}.jpg") # save to disk- The
strinmodelcan be folder name or filename. The file can a video or an image. Refer to ultralytics/predict#inference-sources. - If
streamis false, it calculates at one time. Else, it calculates one time for one loop infor result in results. - You can refer ultralytics/predict documentation.
- The description of attributes like
boxes.xyxycan be found in ultralytics/result.
- Move images into
image_composite/raw_images/backgroundandimage_composite/raw_images/object. - Write parameters into
image_composite/parameters.yaml. - Run image_composite/parameter_test.py while revising parameters.
Whenever run the code, it automatically deletes
image_composite/test/.bg_scale: Scale background image.obj_scale: Scale object image.obj_range: Area for object to be included in.bg_weight: Weight for background image in weighted sum.obj_weight: Weight for object image in weighted sum.gamma: 0-255 value to be added in weighted sum.crop_shape_range: The length of each side of the cropped image is randomly determined within this range. The smallest and largest images is saved inimage_composite\test\images.
- Run gen_data.py to generate dataset.
- Run split_data.py to split dataset into train, validate, test dataset.
- Run detect_train.py after revising it.
- References:
detect_inspect