How to train YOLOv8 bone fracture detection on X-rays

bone fracture detection

Last Updated on 26/11/2025 by Eran Feit

Modern hospitals see thousands of fracture cases every year, and most of them are confirmed or ruled out using X-ray images. Interpreting those X-rays quickly and accurately is critical, but it’s also repetitive, tiring work for radiologists and orthopedic teams. That’s exactly where yolov8 bone fracture detection comes in: it combines state-of-the-art object detection with medical imaging so a model can automatically highlight suspicious fracture regions on an X-ray and support clinical decisions.

At its core, yolov8 bone fracture detection treats fractures like β€œobjects” in the image. Instead of simply saying β€œfracture” or β€œno fracture” for the whole X-ray, the model draws bounding boxes around the areas where it believes a fracture exists and assigns a confidence score. This object-level view is especially useful in complex images where multiple bones, implants, or overlapping structures appear in a single scan, because it shows where the problem is, not just if it exists.

YOLOv8 itself is the latest evolution in the YOLO family, optimized for real-time performance and high accuracy. It uses an efficient backbone and detection head to extract multiscale features from an image and then predicts bounding boxes and class labels in a single forward pass. When you fine-tune YOLOv8 on curated X-ray datasets, it can reach strong mean average precision (mAP) scores for fracture detection, even on challenging pediatric or wrist trauma images.

In practice, a yolov8 bone fracture detection pipeline fits neatly into a real-world workflow. X-ray images are collected and annotated, then split into train, validation, and test sets. The model is trained to recognize fractures as a dedicated class, and once deployed, it processes new X-rays in seconds, drawing boxes around suspected fractures and providing confidence scores. Clinicians can treat the system as a second reader: it doesn’t replace expert judgment, but it helps reduce missed fractures, triage busy emergency departments, and standardize fracture detection across different sites.

Why YOLOv8 bone fracture detection is such a useful approach

YOLOv8 bone fracture detection focuses on a clear target: automatically identifying and localizing fractures on X-ray images so that humans can diagnose faster and with more confidence. The model’s job is to scan each pixel of an X-ray, pick out subtle discontinuities or abnormal shapes along the bone, and turn those patterns into structured predictionsβ€”bounding boxes and labelsβ€”that a clinician can immediately understand. This reduces the cognitive load of scanning dozens or hundreds of images per shift and can highlight cases that deserve a closer look.

At a high level, the workflow starts with data. You collect X-ray images of different bonesβ€”wrists, arms, hips, anklesβ€”and annotate the fracture regions with bounding boxes or points. The dataset is then prepared in a YOLO-friendly format, with separate folders for images and labels, and a YAML file that defines the paths and class names. During training, YOLOv8 learns to map raw pixel patterns to fracture locations by minimizing a loss function that combines localization error, classification error, and confidence scores. Over many epochs, the model refines its ability to distinguish real fractures from normal anatomical structures, implants, and noise.

Once trained, the target in deployment is speed and reliability. An incoming X-ray is resized to the chosen input resolution (for example, 350Γ—350), passed through the YOLOv8 network, and the output is filtered by a confidence threshold. Only boxes above that threshold are drawn on the image, with labels such as β€œFracture” or specific bone types. Because YOLOv8 is designed for real-time object detection, inference remains fast enough to integrate into PACS viewers, emergency triage dashboards, or small clinical decision-support tools without slowing down existing workflows.

Another strength of YOLOv8 bone fracture detection lies in its flexibility. The same architecture can be fine-tuned on datasets for different anatomical regionsβ€”wrist, humerus, pelvis, ribsβ€”or combined with attention modules and ensemble strategies to push mAP even higher. Researchers have already explored variants of YOLOv8 with attention blocks or hybrid pipelines that enhance subtle fracture features and improve robustness across scanners and patient populations. This means you can start with a standard YOLOv8 configuration, like in your code, and later experiment with more advanced variants as your dataset grows or your accuracy requirements become stricter.


yolov8 bone fracture detection
Bone fracture detection

Deep learning tutorials are always easier to follow when the code tells a complete story from start to finish. In this yolov8 bone fracture detection project, the story begins with a clean Python environment, continues with downloading and organizing a medical X-ray dataset, and ends with a trained YOLOv8 model that can highlight fractures directly on real images. The goal is not just to show that YOLOv8 works, but to give you a reproducible pipeline you can run, tweak, and adapt to your own datasets.

The code you’ll see in this tutorial is built around a realistic workflow. It starts by creating a dedicated Conda environment, installing PyTorch with CUDA support, and adding the ultralytics package so YOLOv8 is ready to use. Once the environment is stable, the next step is connecting it to data: a bone fracture dataset exported in YOLOv8 format, with images and labels neatly separated into train and validation folders and tied together through a simple YAML configuration file.

From there, the training script takes over. It loads a YOLOv8 architecture, reads the YAML file that points to the fracture dataset, and launches a long training run with carefully chosen hyperparameters like batch size, number of epochs, image size, and patience. The aim is to let YOLOv8 learn how to detect fractures as a single class called β€œFracture”, using X-ray images resized to 350Γ—350 pixels. This is where the model β€œlearns” to tell the difference between normal bone structure and subtle breaks.

Finally, the tutorial moves into inference and visualization. A second script loads the best trained weights, runs a prediction on a test image, and draws bounding boxes where the model believes a fracture is present. It then reads the ground truth annotation file for the same image, converts YOLO coordinates to pixel coordinates, and visualizes both the model’s prediction and the true bounding box. Seeing these side by side makes it much easier to understand how well your yolov8 bone fracture detection model is performing in practice.

Walking through what this YOLOv8 fracture detection code actually does

At a high level, the target of this code is simple: take a set of labeled X-ray images and train a YOLOv8 model that can automatically detect bone fractures, then compare the model’s predictions to the ground truth. The code is split into logical steps that mirror a real-world workflow: environment setup, dataset download and formatting, training, and prediction plus visualization. By the end, you have both a trained model and a clear way to inspect its performance on individual images.

The first part of the code focuses on the technical foundation. It creates a Conda environment named YoloV8, installs Python 3.8, checks the CUDA version with nvcc --version, and then installs a compatible build of PyTorch, torchvision, torchaudio, and the pytorch-cuda package. After that, it installs ultralytics to get YOLOv8 and lapx for tracking-related functionality. This ensures the rest of the tutorial runs smoothly with GPU acceleration, which is important for long fracture detection training runs.

The next block of code connects the model to data. You download a bone fracture dataset from Roboflow and export it in YOLOv8 format. The folder structure has separate train and valid splits, each with images and labels. The data.yaml file then points to these folders and defines nc: 1 with a single class name ['Fracture']. In the training script, this YAML path is stored in config_file_path, and the project and experiment variables define where YOLOv8 will save logs, checkpoints, and final weights.

The training function is where the main target of the code is realized. It creates a YOLO object from a configuration file (yolov8l.yaml), then calls model.train() with parameters such as epochs=1000, batch=batch_size, imgsz=350, patience=300, and device=0 for GPU usage. These settings let YOLOv8 iteratively improve its fracture detection ability, using early stopping to prevent overfitting. When the training completes, the best-performing weights are saved as best.pt inside the My-model/weights folder.

The final script switches from training to evaluation and visualization. It loads a test X-ray image and its corresponding YOLO label file, then copies the image into imgPredict for drawing predictions. The trained model is loaded from best.pt, and a forward pass returns detection results. For each detection above the chosen confidence threshold, a green bounding box and class name are drawn on the image. In parallel, the script parses the ground truth annotation file, converts normalized YOLO coordinates back to pixel coordinates, and draws the true fracture box on a separate image, imgTruth. By saving and displaying both imgPredict and imgTruth, the code gives you an immediate, visual way to judge how well your yolov8 bone fracture detection model is doing on real X-ray data.


link to the video tutorial : https://youtu.be/elVL9Z8-ZK4

Code for the tutorial here : https://eranfeit.lemonsqueezy.com/buy/5ca38aa5-ddfb-42a6-b158-f15d6e3a40a3 or here : https://ko-fi.com/s/85dad11f25

Link to the dataset : https://universe.roboflow.com/fracture-uofxm/bone-fracture-detection-ivsy6/dataset/1

Link for Medium users : https://medium.com/object-detection-tutorials/how-to-train-yolov8-bone-fracture-detection-on-x-rays-a3be5b3ec372

You can follow my blog here : https://eranfeit.net/blog/

 Want to get started with Computer Vision or take your skills to the next level ?

If you’re just beginning, I recommend this step-by-step course designed to introduce you to the foundations of Computer Vision – Complete Computer Vision Bootcamp With PyTorch & TensorFlow

If you’re already experienced and looking for more advanced techniques, check out this deep-dive course – Modern Computer Vision GPT, PyTorch, Keras, OpenCV4


How to train YOLOv8 bone fracture detection on X-rays

Building a deep learning model always feels more powerful when you see it work on a real medical task.
In this tutorial we’ll walk through a complete yolov8 bone fracture detection pipeline, from setting up a clean environment to training the model and visualizing predictions on X-ray images.

The goal is simple.
We want YOLOv8 to look at an X-ray, find the fracture region, and draw a bounding box around it with a β€œFracture” label.
To get there, we’ll prepare a YOLOv8-ready dataset, connect it via data.yaml, train a custom detector, and then compare YOLOv8 predictions with the ground truth boxes.

All the code is broken into digestible parts so you can copy, paste, and adapt it.
If you already used my other YOLOv8 tutorials, you’ll recognise the same pattern: Conda environment β†’ dataset in YOLO format β†’ YAML config β†’ training script β†’ inference script.
Here we simply specialize that workflow for bone fracture detection on X-rays.

Getting the environment ready for YOLOv8 bone fracture detection

Before training any model, you want an isolated environment where dependencies won’t conflict with other projects.
This first block creates a dedicated Conda environment, installs PyTorch with CUDA 11.8, and adds the Ultralytics YOLOv8 package plus an extra dependency used by the library.

### Create a dedicated Conda environment named YoloV8 with Python 3.8 so all yolov8 bone fracture detection dependencies stay isolated.
conda create --name YoloV8 python=3.8

### Activate the new YoloV8 environment so every subsequent install and command runs inside this clean setup.
conda activate YoloV8

### Check the installed CUDA toolkit version to confirm that nvcc is available and matches the version you plan to use with PyTorch.
nvcc --version

### Install PyTorch, torchvision, and torchaudio compiled against CUDA 11.8 so training can run efficiently on the GPU.
conda install pytorch==2.1.1 torchvision==0.16.1 torchaudio==2.1.1 pytorch-cuda=11.8 -c pytorch -c nvidia

### Install the Ultralytics package that provides the YOLOv8 implementation used for bone fracture detection.
pip install ultralytics==8.1.0

### Install the lapx package, which Ultralytics uses for certain tracking and post-processing utilities.
pip install lapx>=0.5.2

After running these commands you have a clean, reproducible setup ready for training YOLOv8.
If something breaks later, you know exactly which environment and versions to recreate on another machine.


Preparing the bone fracture X-ray dataset in YOLOv8 format

Next we need a dataset of bone fracture X-rays with labels in YOLOv8 format.
The dataset you’re using is downloaded from Roboflow as a YOLOv8 export at 350Γ—350 resolution, and then unpacked into a simple folder structure under C:/Data-sets/Bone fracture detection.

### Download the bone fracture detection dataset from Roboflow in YOLOv8 format so that images and label TXT files are already compatible with YOLOv8 training.
# Bone fracture detection dataset exported in YOLOv8 format at 350x350 resolution.

### Unzip the dataset under a clear base directory so YOLOv8 can find the images and labels.
# Base folder:
# C:/Data-sets/Bone fracture detection

### Make sure the dataset is split into train, validation, and test sets with separate images and labels folders.
C:/Data-sets/Bone fracture detection/
    train/
        images/
        labels/
    valid/
        images/
        labels/
    test/
        images/
        labels/

This simple layout is exactly what YOLOv8 expects.
Each image in images/ has a matching .txt file in labels/ describing the fracture bounding boxes in YOLO format.


Pointing YOLOv8 to the fracture dataset with data.yaml

YOLOv8 needs a small YAML file that tells it where the images live and what classes exist in the dataset.
For this project we have a single class called Fracture, and we store the YAML file under the project’s configuration folder.

train: C:/Data-sets/Bone fracture detection/train/images
val: C:/Data-sets/Bone fracture detection/valid/images

# class names
nc: 1
names: ['Fracture']

With this YAML file in place, YOLOv8 can connect images, labels, and class names into a single configuration.
You’ll reference this file in the training script through the data argument.


Training the YOLOv8 model to detect bone fractures

Now we move to the heart of the tutorial.
This script loads a YOLOv8 model, points it at the fracture dataset via data.yaml, and launches a long training run with early stopping.

### Import the YOLO class from the ultralytics package so we can configure and train our yolov8 bone fracture detection model.
from ultralytics import YOLO


### Define a main function that encapsulates the full training workflow for clarity and reuse.
def main():

    ### Load the YOLOv8 large model configuration so we start from a strong backbone for bone fracture detection.
    model = YOLO("yolov8l.yaml")

    ### Set the path to the YAML configuration file that points YOLOv8 to the bone fracture X-ray dataset.
    config_file_path = "Best-Object-Detection-models/Yolo-V8/Bone Fracture Detection/data.yaml"

    ### Define the base project folder where YOLOv8 will store runs, logs, and trained weights for this fracture detection task.
    project = "C:/Data-sets/Bone fracture detection"

    ### Choose a name for this specific experiment so multiple runs remain clearly separated inside the project folder.
    experiment = "My-Model"

    ### Set the batch size for training and reduce it to 16 if you encounter GPU memory issues.
    batch_size = 32

    ### Call the train method to start optimizing the YOLOv8 model on the bone fracture dataset with your chosen hyperparameters.
    result = model.train(
        data=config_file_path,
        epochs=1000,
        project=project,
        name=experiment,
        batch=batch_size,
        device=0,
        patience=300,
        imgsz=350,
        verbose=True,
        val=True
    )


### Ensure the main function is only executed when this script is run directly rather than imported as a module.
if __name__ == "__main__":
    main()

This code will create a new run under C:/Data-sets/Bone fracture detection/My-Model.
Inside the weights folder you’ll find best.pt, which contains the best performing YOLOv8 model for your yolov8 bone fracture detection task.

Running predictions and comparing with ground truth X-ray labels

Once training is done, it’s time to see how the model performs on real images.
The following script loads the trained weights, runs inference on a test X-ray, and then draws both predicted and ground truth boxes so you can compare them visually.

### Import the YOLO class so we can load the trained weights and run fracture detection on new X-ray images.
from ultralytics import YOLO

### Import OpenCV to handle image loading, drawing bounding boxes, and displaying windows.
import cv2

### Import the os module to build file paths in a robust and portable way.
import os


### Define the path to a test X-ray image that the yolov8 bone fracture detection model did not see during training.
imgTest = "C:/Data-sets/Bone fracture detection/test/images/all_0_2324_png.rf.64c3541a9e2a4eafb1730138f27ac1e5.jpg"

### Define the path to the YOLO label file that contains the ground truth fracture annotation for the same test image.
imgAnot = "C:/Data-sets/Bone fracture detection/test/labels/all_0_2324_png.rf.64c3541a9e2a4eafb1730138f27ac1e5.txt"


### Read the test image from disk into a NumPy array so OpenCV and YOLOv8 can process it.
img = cv2.imread(imgTest)

### Extract the image height and width, which are needed to convert normalized YOLO coordinates to pixel coordinates later.
H, W, _ = img.shape


### Create a copy of the original image that will be used to draw YOLOv8 prediction bounding boxes.
imgPredict = img.copy()

### Build the full path to the best set of trained weights produced by the YOLOv8 training run.
model_path = os.path.join("C:/Data-sets/Bone fracture detection", "My-model", "weights", "best.pt")


### Load the trained YOLOv8 model from disk so it is ready to run bone fracture detection on the test image.
model = YOLO(model_path)

### Set a confidence threshold so only high-confidence fracture predictions are drawn.
threshold = 0.5


### Run the model on the prediction image and take the first result object for easier access to detections.
results = model(imgPredict)[0]

### Loop over each detected bounding box, confidence score, and class ID returned by YOLOv8.
for result in results.boxes.data.tolist():
    ### Unpack the raw detection values into separate variables.
    x1, y1, x2, y2, score, class_id = result

    ### Convert the floating point box coordinates to integers for OpenCV drawing functions.
    x1 = int(x1)
    y1 = int(y1)
    x2 = int(x2)
    y2 = int(y2)

    ### Only keep detections whose confidence is above the chosen threshold.
    if score > threshold:
        ### Draw a green rectangle around the predicted fracture region on the prediction image.
        cv2.rectangle(imgPredict, (x1, y1), (x2, y2), (0, 255, 0), 1)

        ### Look up the class name from the results dictionary and convert it to uppercase for display.
        class_name = results.names[int(class_id)].upper()

        ### Render the class label text just above the bounding box on the prediction image.
        cv2.putText(
            imgPredict,
            class_name,
            (x1, y1 - 10),
            cv2.FONT_HERSHEY_SIMPLEX,
            0.5,
            (0, 255, 0),
            1,
            cv2.LINE_AA
        )


### Create another copy of the original image that will be used to draw ground truth fracture boxes.
imgTruth = img.copy()

### Open the annotation text file and read all lines so we can parse the YOLO labels.
with open(imgAnot, "r") as file:
    lines = file.readlines()

### Prepare an empty list that will store parsed annotation tuples.
annotations = []

### Loop over each line in the annotation file.
for line in lines:
    ### Split the line into individual string values representing label and box coordinates.
    values = line.split()

    ### The first value is the class label index.
    label = values[0]

    ### The remaining values are the normalized x center, y center, width, and height of the box.
    x, y, w, h = map(float, values[1:])

    ### Append the parsed annotation as a tuple so we can process all boxes later.
    annotations.append((label, x, y, w, h))


### Loop over each parsed annotation to draw the ground truth boxes.
for annotation in annotations:
    ### Unpack the stored label index and normalized box coordinates.
    label, x, y, w, h = annotation

    ### Convert the label index into the same uppercase class name used for predictions.
    label = results.names[int(label)].upper()

    ### Convert the normalized YOLO coordinates into top-left and bottom-right pixel coordinates.
    x1 = int((x - w / 2) * W)
    y1 = int((y - h / 2) * H)
    x2 = int((x + w / 2) * W)
    y2 = int((y + h / 2) * H)

    ### Draw a green rectangle around the ground truth fracture region on the ground truth image.
    cv2.rectangle(imgTruth, (x1, y1), (x2, y2), (0, 255, 0), 1)

    ### Render the ground truth label text just above the ground truth bounding box.
    cv2.putText(
        imgTruth,
        label,
        (x1, y1 - 5),
        cv2.FONT_HERSHEY_SIMPLEX,
        0.5,
        (0, 255, 0),
        1
    )


### Save the ground truth image with boxes to disk so you can inspect it outside the script if needed.
cv2.imwrite("c:/temp/imgTruth.png", imgTruth)

### Display the prediction image in a window so you can see the YOLOv8 fracture detections.
cv2.imshow("Image Predict", imgPredict)

### Display the ground truth image in another window for visual comparison.
cv2.imshow("Image Truth", imgTruth)

### Optionally display the original image without any boxes for reference.
cv2.imshow("img", img)

### Wait indefinitely for a key press before closing the OpenCV windows.
cv2.waitKey(0)

By comparing imgPredict and imgTruth you can quickly see how well the model lines up with the human annotations.
This side-by-side view is often more intuitive than staring at metrics alone.


FAQ: YOLOv8 bone fracture detection

What is YOLOv8 bone fracture detection?

YOLOv8 bone fracture detection is a custom object detection model that learns to locate fractures on X-ray images and draw bounding boxes around suspicious regions.

Which dataset format should I use for this tutorial?

Use a YOLOv8-formatted dataset with train, valid, and test folders, where each image has a matching TXT file that stores class IDs and normalized bounding box coordinates.

Do I need a GPU to train the fracture detection model?

A GPU is highly recommended because training on medical images for many epochs is slow on CPU, but you can still run a smaller experiment without a GPU by lowering the batch size and epochs.

Why is the image size set to 350×350 in training?

The dataset is exported at 350×350, and keeping the same resolution provides a good balance between fracture detail and computational cost during YOLOv8 training.

What does the patience setting control in YOLOv8 training?

The patience parameter controls early stopping by telling YOLOv8 how many epochs to wait for validation improvement before stopping to prevent unnecessary overfitting.

How can I update the paths to match my local folders?

Edit the paths in data.yaml, the project variable in the training script, and the image and label paths in the prediction script so they point to your own dataset directory.

Can I add more classes besides fractures?

Yes, you can label additional classes such as implants or foreign objects, increase nc in data.yaml, and expand the names list so YOLOv8 learns to detect multiple categories.

What confidence threshold should I start with?

A starting threshold of 0.5 works well for many setups, and you can tune it higher to reduce false positives or lower it to reveal more potential fracture candidates.

How do I check if my model is overfitting the bone fracture dataset?

Compare training and validation losses; if training loss continues to drop while validation loss rises, the model is likely overfitting and you may need more data or stronger augmentation.

Can this YOLOv8 pipeline be reused for non-medical projects?

The same pipeline can train YOLOv8 on any YOLO-formatted dataset, so you can swap the fracture images for everyday objects and reuse the environment, training code, and inference logic.


Conclusion

By now you have a complete yolov8 bone fracture detection workflow that you can run end to end on your own machine.
You set up a clean GPU-ready Conda environment, prepared a YOLOv8-compatible bone fracture dataset, connected it through a simple data.yaml file, and trained a YOLOv8 model that learns to highlight fractures on X-ray images.

Just as importantly, you saw how to move from training metrics to visual understanding by drawing both prediction and ground truth boxes on the same X-ray.
This comparison helps you quickly spot missed fractures, overly large boxes, or noisy predictions and then loop back to improve the dataset or hyperparameters.

The same structure scales beyond this one project.
You can adapt the code to other bones, other medical imaging modalities, or even non-medical objects simply by swapping the dataset and adjusting the YAML configuration.
Once you’re comfortable with this pattern, YOLOv8 becomes a reusable tool you can bring into many real-world computer vision problems.

Connect :

β˜• Buy me a coffee β€” https://ko-fi.com/eranfeit

πŸ–₯️ Email : feitgemel@gmail.com

🌐 https://eranfeit.net

🀝 Fiverr : https://www.fiverr.com/s/mB3Pbb

Enjoy,

Eran

Leave a Comment

Your email address will not be published. Required fields are marked *

Eran Feit