So, I'm trying to train a YOLO classification model on a custom dataset that contains jpg-images of two different classes. But when I launch training, I get following error:
Traceback (most recent call last):
  File "C:\pythonProject\main.py", line 5, in <module>
    model.train(data='./training_dataset', epochs=1, imgsz=64)
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\engine\model.py", line 341, in train
    self.trainer.train()
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\engine\trainer.py", line 192, in train
    self._do_train(world_size)
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\engine\trainer.py", line 288, in _do_train
    self._setup_train(world_size)
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\engine\trainer.py", line 255, in _setup_train
    self.test_loader = self.get_dataloader(self.testset, batch_size=batch_size * 2, rank=-1, mode='val')
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\models\yolo\classify\train.py", line 88, in get_dataloader
    dataset = self.build_dataset(dataset_path, mode)
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\models\yolo\classify\train.py", line 83, in build_dataset
    return ClassificationDataset(root=img_path, args=self.args, augment=mode == 'train', prefix=mode)
  File "C:\pythonProject\venv\lib\site-packages\ultralytics\data\dataset.py", line 220, in __init__
    super().__init__(root=root)
  File "C:\pythonProject\venv\lib\site-packages\torchvision\datasets\folder.py", line 309, in __init__
    super().__init__(
  File "C:\pythonProject\venv\lib\site-packages\torchvision\datasets\folder.py", line 145, in __init__
    samples = self.make_dataset(self.root, class_to_idx, extensions, is_valid_file)
  File "C:\pythonProject\venv\lib\site-packages\torchvision\datasets\folder.py", line 189, in make_dataset
    return make_dataset(directory, class_to_idx, extensions=extensions, is_valid_file=is_valid_file)
  File "C:\pythonProject\venv\lib\site-packages\torchvision\datasets\folder.py", line 61, in make_dataset
    directory = os.path.expanduser(directory)
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\ntpath.py", line 293, in expanduser
    path = os.fspath(path)
TypeError: expected str, bytes or os.PathLike object, not NoneType

I've tried two different datasets and that problem occured on both of them.
My full code:
from ultralytics import YOLO

model = YOLO('yolov8n-cls.pt')

model.train(data='./training_dataset', epochs=1, imgsz=64)

Dataset structure:
training_dataset/train/cats;
training_dataset/train/dogs


I have trained my YoloV8 detection model.
After training the model there are plenty of files stored within in the train folder.
One of the files are the train_batch.jpg and the val_batch.jpg.
The images within the train_batch.jpg are cutted of and scrambled.

The images within the val_batch.jpg looks fine.

The imagesize of the images within train_batch and val_batch are the same.
Does someone know if this is a problem?
I have tried to change the image sizes and used various batch sizes.


What are the class IDs and their corresponding class names for YOLOv8 models? I understand there are approximately 80 classes in the object detection model of YOLOv8. However, I'm looking to specifically identify each class along with their respective class IDs. Additionally, do all YOLO models (yolov3, yolov5, yolov7, yolov8) have the same number of classes and corresponding class IDs?


I need some help as I will be needing this to work for my final thesis project for the Model has 2 classes inheat and non-inheat, I did the codes here below but when it tries to predict or detect by frames of the video it detects the non-inheat but it only stacks in the ininheat frames instead of the non_ inheat frames I might be doing a wrong process here for by frames in stacking them up even its detecting non-inheat it stacks to the in_heat frames.
codes:
def process_video_with_second_model(video_path):
    cap = cv2.VideoCapture(video_path)
    class_counts = {'inheat': 0, 'non-inheat': 0}

    in_heat_frames = []
    non_in_heat_frames = []

    while True:
        ret, frame = cap.read()
        if frame is None:
            break # Break the loop when no more frames are available

        # Resize the frame to a smaller size (e.g., 400x400)
        frame_small = cv2.resize(frame, (400, 400))

        # Use the second model to detect in-heat behavior
        results_in_heat = yolov8_model_in_heat.predict(source=frame_small, show=True, conf=0.8)

        # Print results to inspect structure
        for results_in_heat_instance in results_in_heat:
            # Access bounding box coordinates
            boxes = results_in_heat_instance.boxes

            # CONFIDENCE 0.5
            if len(boxes) > 0:
                class_name = results_in_heat_instance.names[0]

                # Use a dictionary to store the counts for each class
                class_counts[class_name] += 1

                # Add the frame to the corresponding list based on the class name
                if class_name == 'non-inheat':
                    non_in_heat_frames.append(frame)
                elif class_name == 'inheat':
                    in_heat_frames.append(frame)

        print(f"Class Counts: {class_counts}")

        # Check if either condition is met (50 frames for inheat and 50 frames for non-inheat)
        if class_counts['inheat'] >= 50 and class_counts['non-inheat'] >= 50:
            break

    # Release resources for the second model
    cap.release()
    cv2.destroyAllWindows()

    # Stack the in-heat and non-in-heat frames vertically
    stacked_in_heat_frames = np.vstack(in_heat_frames)
    stacked_non_in_heat_frames = np.vstack(non_in_heat_frames)

    # Display the stacked in-heat and non-in-heat frames
    cv2.imshow('Stacked In-Heat Frames', stacked_in_heat_frames)
    cv2.imshow('Stacked Non-In-Heat Frames', stacked_non_in_heat_frames)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    # Compare the counts and return the label with the higher count
    if class_counts['inheat'] > class_counts['non-inheat']:
        return 'inheat'
    elif class_counts['non-inheat'] > class_counts['inheat']:
        return 'non-inheat'

I did read the YOLOv8 Documents for predicting but still cant do it. I did this in the Pycharm IDE


I am using Ultralytics YOLO for license plate detection, and I'm encountering an issue when trying to extract bounding box coordinates from the Results.boxes object. I have inspected the structure of the Results.boxes object, but I am having difficulty accessing the bounding box information correctly.
class ImageProcessing:
    def __init__(self, model_path: Path, input_image: Path, output_image: Path):
        if not isinstance(model_path, Path):
            raise TypeError("model_path must be a pathlib.Path instance")
        if not isinstance(input_image, Path) or not isinstance(output_image, Path):
            raise TypeError("input_image and output_image must be pathlib.Path instances")
        # Load the YOLO model from the provided path
        self.model = YOLO(str(model_path))
        self.input_image = input_image
        self.output_image = output_image

    def ascertain_license_plates_as_image(self, threshold: float = 0.5, fontscale: float = 1.3, color: tuple = (0, 255, 0), thickness: int = 3):
        image = opencv.imread(str(self.input_image))
        results = self.model(image)

        # Check if results is a list and get the first result
        if isinstance(results, list):
            results = results[0]

        # Iterate through each detected object
        for box in results.boxes:
            # Extract coordinates, confidence, and class ID
            x1, y1, x2, y2, conf, class_id = box.data[0][0], box.data[0][1], box.data[0][2], box.data[0][3], box.conf.item(), int(box.cls.item())
            if conf > threshold:
                opencv.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), color, thickness)
                label = results.names[class_id].upper() if results.names else f'class {class_id}'
                opencv.putText(image, label, (int(x1), int(y1) - 10), opencv.FONT_HERSHEY_SIMPLEX, fontscale, color, thickness, opencv.LINE_AA)

        opencv.imwrite(str(self.output_image), image)
        return results

However, I'm getting an IndexError, and it seems that my indexing might be incorrect for this particular Boxes object. Or even worse, cv2 is not highlighting the license plate.


I’ve custom trained a yolov8n model and I would like to run it on a Jetson Nano. Has anyone managed to do this? If yes, would you be so kind to help me out?
I’ve got a .pt of the custom trained model. The OS image offered by NVidia on their website is an Ubuntu 18.04 and I have run into many compatibility issues. I’m interested in finding out if anyone has managed to get yolo running on the Jetson specifically the yolov8n model from ultralytics.
Thanks in advance!


I'm currently working on an object detection project using YOLOv8 and a customized dataset. In my dataset, each image is accompanied by its corresponding label file (Data_1.png -> Data_1.txt).
The label file Data_1.txt follows the format:
Class_type, x_1 min, y_1 min, ..., x_4 min, y_4 min.

I'm interested in applying a perspective augmentation to my dataset, and I've decided to use the YOLOv8 augmentation functionality. However, I am unsure whether YOLOv8 generates labels for the augmented data or not. If it does not, I would greatly appreciate any suggestions or alternative approaches to handle the generation of labels for the augmented data.


How do I get the class names of segmented instances when detecting multiple classes in YOLOv8? The detections do not have a .cls attribute like here YOLOv8 get predicted class name. Also the docs do not seem to mention anything e.g. here
When I use the show=true argument in the prediction function, the classes are distinguished in the resulting image, but I cannot get them programmatically. My code that gets me all detections I wanjt but does not let me know which one is which:
from ultralytics import YOLO
model = YOLO("path/to/best.pt")
result = model.predict(os.path.join(cut_dir, im_name), save_conf=True, show=True)
if result[0].masks is not None:
    for counter, detection in enumerate(result[0].masks.data):
         detected = np.asarray(detection.cpu())


I want to close the detection window on a key press and not have to stop the entire code. I am able to do it for my image detection but since video runs on a loop I can't find how.
            root.video = filedialog.askopenfilename(initialdir="/desktop", title="Select video to detect")
            cap = cv2.VideoCapture(root.video)

            model = YOLO('best.pt')

            classNames = ['Orange', 'Orange', 'Pomegranate', 'Pomegranate', 'apple', 'apple', 'banana', 'banana',
                          'fruits', 'guava', 'guava', 'guava', 'lime', 'lime']
            while True:
                success, vid = cap.read()
                results = model(img, stream=True)

                        cv2.imshow("DetectVideo", vid)
                        cv2.waitKey(1)

I have tried the following
k = cv2.waitKey(0) #also tried with (1)
print(k)
if k == 27:  # close on ESC key
    cv2.destroyAllWindows()

which basically makes it so it just closes each frame of the video then continues to next frame on key press.


def extract_and_process_tracks(self, tracks):
    boxes = tracks[0].boxes.xyxy.cpu()
    clss = tracks[0].boxes.cls.cpu().tolist()
    track_ids = tracks[0].boxes.id.int().cpu().tolist()

    self.annotator = Annotator(self.im0, self.tf, self.names)
    self.annotator.draw_region(reg_pts=self.reg_pts, color=(0, 255, 0))

    for box, track_id, cls in zip(boxes, track_ids, clss):
        self.annotator.box_label(box, label=self.names[cls], color=colors(int(cls), True))

        # Draw Tracks
        track_line = self.track_history[track_id]
        track_line.append((float((box[0] + box[2]) / 2), float((box[0] + box[2]) / 2))
        track_line.pop(0) if len(track_line) > 30 else None

        if self.draw_tracks:
            self.annotator.draw_centroid_and_tracks(track_line,
                                                    color=(0, 255, 0),
                                                    track_thickness=self.track_thickness)

The object_counter.py provided by ultralytics can achieve the counting job, the track_line.append store the center of the
box(float((box[0] + box[2]) / 2), float((box[0] + box[2]) / 2),
but how to change the center into the keypoints coordinate, e.g. I want to count the head keypoints of animal cross a specified line.
How to get the keypoints coordinate in yolo_pose?


I have my own pre-trained YOLO model, and I want to have different colors of LEDs light up on Arduino Uno breadbroad when different labels are being detected from my webcam.
So, I was thinking of first assigning the command for different LEDs to light up. ("G" for green led, "R" for red led, "Y" for yellow led, "A" for turning both red and yellow led at the same time, and "0" to turn off all led.
)
I started with my Arduino code as below:
char command;

void setup() {
    Serial.begin(9600);
    pinMode(2, OUTPUT);  // Green LED pin
    pinMode(3, OUTPUT);  // Red LED pin
    pinMode(4, OUTPUT);  // Yellow LED pin
}

void loop() {
    if (Serial.available() > 0) {
        command = Serial.read();
        if (command == 'G') {
            // Turn on green LED
            digitalWrite(2, HIGH);
            digitalWrite(3, LOW);  // Turn off red LED
            digitalWrite(4, LOW);  // Turn off yellow LED
        } else if (command == 'R') {
            // Turn on red LED
            digitalWrite(2, LOW);   // Turn off green LED
            digitalWrite(3, HIGH);
            digitalWrite(4, LOW);   // Turn off yellow LED
        } else if (command == 'Y') {
            // Turn on yellow LED
            digitalWrite(2, LOW);   // Turn off green LED
            digitalWrite(3, LOW);   // Turn off red LED
            digitalWrite(4, HIGH);
        } else if (command == 'A') {
            // Turn on both red and yellow LEDs
            digitalWrite(2, LOW);   // Turn off green LED
            digitalWrite(3, HIGH);
            digitalWrite(4, HIGH);
        } else if (command == '0') {
            // Turn off all LEDs
            digitalWrite(2, LOW);
            digitalWrite(3, LOW);
            digitalWrite(4, LOW);
        }
    }
}

In my YOLO model, there are three classes
#Classes
names:
  0: aaa
  1: bbb
  2: ccc

Therefore, for my python code I started with first turning on the webcam and loading then using serial library to connect to arduino.
from ultralytics import YOLO
import serial
import time
import sys

# Load my YOLO model using
model = YOLO("best.pt")

# Open the serial port for communication with Arduino
arduino = serial.Serial('COM3', 9600)  # Change 'COM3' to your Arduino port

after that, I want to assign the labels with command to Arduino, and I also try to do a little
# Map the class labels to corresponding Arduino commands
label_commands = {
    'aaa': 'G',
    'bbb': 'R',
    'ccc': 'Y',
    'aaa_bbb': 'A',
    'aaa_bbb_ccc': 'A',
    'none': '0'
}

while True:
    try:
        results = model.predict(source="0", show=True)  # assumes '0' is your source identifier

        # Extract the detected labels from results
        detected_labels = [item['label'] for item in results.xyxy[0].numpy()]

        # Determine the Arduino command based on detected labels
        if 'aaa' in detected_labels and 'bbb' in detected_labels and 'ccc' in detected_labels:
            command = label_commands['aaa_bbb_ccc']
        elif 'aaa' in detected_labels and 'bbb' in detected_labels:
            command = label_commands['aaa_bbb']
        elif 'aaa' in detected_labels:
            command = label_commands['aaa']
        elif 'bbb' in detected_labels and 'ccc' in detected_labels:
            command = label_commands['aaa_bbb_ccc']
        elif 'bbb' in detected_labels:
            command = label_commands['bbb']
        elif 'ccc' in detected_labels:
            command = label_commands['ccc']
        else:
            command = label_commands['none']

        # Print the command for debugging
        print(f"Sending command to Arduino: {command}")
        sys.stdout.flush()  # Flush the standard output

        # Send the command to Arduino
        arduino.write(command.encode())

    except Exception as e:
        print(f"Error: {e}")
        sys.stdout.flush()  # Flush the standard output

    # Wait for 5 seconds before sending the next command
    time.sleep(5)

BUT, this part of code doesn't work at all. I know my arduino is connected for sure, and I have also tested with from randoming sending the letter command to arduino from python, which worked perfectly.
Also when I run this code, the run window are showing only things like:
1/1: 0... Success ✅ (inf frames of shape 640x480 at 25.00 FPS)

WARNING ⚠ inference results will accumulate in RAM unless `stream=True` is passed, causing potential out-of-memory
errors for large sources or long-running streams and videos. See https://docs.ultralytics.com/modes/predict/ for help.

Example:
    results = model(source=..., stream=True)  # generator of Results objects
    for r in results:
        boxes = r.boxes  # Boxes object for bbox outputs
        masks = r.masks  # Masks object for segment masks outputs
        probs = r.probs  # Class probabilities for classification outputs

0: 480x640 (no detections), 141.0ms
0: 480x640 1 aaa, 182.2ms
0: 480x640 1 aaa, 134.3ms
0: 480x640 1 aaa, 122.1ms
0: 480x640 (no detections), 121.4ms
0: 480x640 (no detections), 147.5ms
0: 480x640 (no detections), 131.5ms
0: 480x640 (no detections), 140.3ms
0: 480x640 1 aaa, 127.1ms
0: 480x640 1 aaa, 124.1ms
0: 480x640 1 aaa, 123.2ms
0: 480x640 1 aaa, 172.2ms
...

even with my debugging script, it doesn't tell me what command is being sent to the arduino broad
        # Print the command for debugging
        print(f"Sending command to Arduino: {command}")
        sys.stdout.flush()  # Flush the standard output


can you please help me.........
I have my custom trained model (best.pt), it detects two things person and headlight. Now I want the output according to these conditions: 1. If model detect only headlight return 0, 2. If model detect only person return 1, 3. If model detect headlight and person both return 0.
import cv2
from ultralytics import YOLO

video_path = 'data/video1.mp4'
video_out_path = 'out.mp4'

cap = cv2.VideoCapture(video_path)

# Check if the video file is opened successfully
if not cap.isOpened():
    print("Error: Could not open the video file.")
    exit()

ret, frame = cap.read()

# Check if the first frame is read successfully
if not ret:
    print("Error: Could not read the first frame from the video.")
    exit()

cap_out = cv2.VideoWriter(video_out_path, cv2.VideoWriter_fourcc(*'MP4V'), cap.get(cv2.CAP_PROP_FPS),
                          (int(cap.get(3)), int(cap.get(4))))  # Use cap.get(3) and cap.get(4) for width and height

model = YOLO("bestall5.pt")

detection_threshold = 0.5
while ret:
    results_list = model(frame)

    headlight_detected = False
    person_detected = False

    # Iterate through the list of results
    for results in results_list:
        # Check if the current result has the necessary attributes
        if hasattr(results, 'xyxy'):
            for result in results.xyxy:
                x1, y1, x2, y2, score, class_id = result.tolist()
                x1, x2, y1, y2 = int(x1), int(x2), int(y1), int(y2)

                # Assuming class_id is the index of the class in the model's class list
                class_name = model.names[class_id]

                if class_name == "headlight" and score > detection_threshold:
                    headlight_detected = True
                elif class_name == "person" and score > detection_threshold:
                    person_detected = True

    # Output based on the specified conditions
    if headlight_detected and person_detected:
        output = 0
    elif headlight_detected:
        output = 0
    elif person_detected:
        output = 1
    else:
        output = -1  # No person or headlight detected

    print("Output:", output)

    cap_out.write(frame)

    cv2.imshow('Object Detection', frame)

    # Break the loop if 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

    ret, frame = cap.read()

cap.release()
cap_out.release()
cv2.destroyAllWindows()

I tried this but getting only -1 as output but my video has both headlight and person


I am currently working with YOLOv8 and I'm wondering if there is a method similar to results.pandas().xyxy available in YOLOv5 to obtain structured results in tabular form.
With YOLOv5, it's possible to get results easily using the following code:
results = model(img)
df = results.pandas().xyxy[0]  # Get results in tabular format
print(df)
#      xmin    ymin    xmax   ymax  confidence  class    name
# 0  749.50   43.50  1148.0  704.5    0.874023      0  person
# 1  433.50  433.50   517.5  714.5    0.687988     27     tie
# 2  114.75  195.75  1095.0  708.0    0.624512      0  person
# 3  986.00  304.00  1028.0  420.0    0.286865     27     tie


When my nn starts learning, the kernel crashes
The Kernel crashed while executing code in the current cell or a previous cell.

Please review the code in the cell(s) to identify a possible cause of the failure.

Click here for more info.

View Jupyter log for further details.

Yolo doesn't use my GPU resources for learning instead it trying to use CPU and I think that it is a reason why kernel crashes.
How I can fix it?
screenshot
I tried to install CUDA 7.5 (for my RTX 2060). I recently started to study neural networks and I am not sure that I need CUDA.
I also checked similar topics here but I am not sure that there is my case.


Let's say I have a folder called 'test' with folders inside, 'images' and 'labels'. I also have a YOLOv8 model which I've trained called 'best.pt. My labels are polygons (yolo-obb .txt files).
I want to find the mean average precision (MAP) of my YOLOv8 model on this test set.
I've read both the documentation for predicting and benchmarking, however, I'm struggling to find an example of calculating map from some test images.
https://docs.ultralytics.com/modes/predict/
https://docs.ultralytics.com/modes/benchmark/
from ultralytics import YOLO

# Load a pretrained YOLOv8n model
model = YOLO('best.pt')

# Run inference on an image
results = model(['test/images/bus.jpg', 'test/images/zidane.jpg'])  # list of 2 Results objects

I imagine I have to put the list of images in the above, then write code to calculate map for everything in the test folder and average it. Are there packages that have already done this?
What's the code to achieve this task?


I have the following code
from ultralytics import YOLO
import cv2
import math
import os
import time

# Start webcam
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)

# Load custom model
model_path = os.path.join('.', 'runs', 'detect', 'train', 'weights', 'last.pt')
model = YOLO(model_path)  # load a custom model

# Define your custom object classes
classNames = ["reese_pretzel"]  # Update with your custom classes

# Confidence threshold
confidence_threshold = 0.5

# Initialize variables for tracking time
start_time = None
end_time = None
object_detected = False

while True:
    success, img = cap.read()
    results = model(img, stream=True)

    # Process results
    for r in results:
        boxes = r.boxes

        for box in boxes:
            # Extract box coordinates
            x1, y1, x2, y2 = box.xyxy[0]
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)

            # Confidence
            confidence = math.ceil((box.conf[0]*100))/100

            # Check confidence threshold
            if confidence > confidence_threshold:
                # Class name
                cls = int(box.cls[0])
                class_name = classNames[cls]

                # Draw bounding box
                cv2.rectangle(img, (x1, y1), (x2, y2), (255, 0, 255), 3)

                # Object details
                org = [x1, y1]
                font = cv2.FONT_HERSHEY_SIMPLEX
                fontScale = 1
                color = (255, 0, 0)
                thickness = 2

                cv2.putText(img, class_name, org, font, fontScale, color, thickness)

                # Set start time when an object is first detected
                if not object_detected:
                    start_time = time.time()
                    object_detected = True
            else:
                # Reset start time when no object is detected
                start_time = None
                object_detected = False

    cv2.imshow('Webcam', img)
    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

I keep getting outputs to my console like
0: 480x640 (no detections), 49.2ms
Speed: 0.9ms preprocess, 49.2ms inference, 0.2ms postprocess per image at shape (1, 3, 480, 640)

or
0: 384x640 1 reese_pretzel, 75.0ms
Speed: 4.8ms preprocess, 75.0ms inference, 0.3ms postprocess per image at shape (1, 3, 384, 640)

Where are these messages getting printed from?
I tried looking at the YOLO model.py file but that too doesn't have any print statements in it. I want to do something like if there are no detections, print('no detect), and if something is detected, print the name of the object.


When training a Yolo model like below:
from ultralytics import YOLO

# Load a model
model = YOLO('yolov8s.pt')

results = model.train(data='coco128.yaml',
epochs=100, imgsz=640, save_period=1)

The save_period option will save every epoch. When the best epoch is found the file is saved as best.pt.
The file size of best.pt is ~27MB and each epoch is ~120MB. Is it possible to use the compression applied to the best epoch at the end of training to every epoch (even if this is done after training).


I'm encountering a problem with creating space after uploading app.py and requirements.txt. For loading the model, I'm using this code: from ultralyticsplus import YOLO, render_result.
(I use Gradio to create a website.)
The main task for uploading app.py to the space is that I want the HTML code to be embedded on the Google site.
model_path = ('(my model path on huggingface')
model = YOLO(model_path)

If I use another method to load the model instead of using YOLO, is it possible to fix this error?
The error said
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/ultralyticsplus/ultralytics_utils.py", line 59, in __init__
    self._load_from_hf_hub(model, hf_token=hf_token)
  File "/usr/local/lib/python3.10/site-packages/ultralyticsplus/ultralytics_utils.py", line 91, in _load_from_hf_hub
    ) = self._assign_ops_from_task()
  File "/usr/local/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1614, in __getattr__
    raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'YOLO' object has no attribute '_assign_ops_from_task'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/user/app/app.py", line 95, in <module>
    gr.Interface(fn=detect_objects,
  File "/usr/local/lib/python3.10/site-packages/gradio/interface.py", line 518, in __init__
    self.render_examples()
  File "/usr/local/lib/python3.10/site-packages/gradio/interface.py", line 851, in render_examples
    self.examples_handler = Examples(
  File "/usr/local/lib/python3.10/site-packages/gradio/helpers.py", line 71, in create_examples
    examples_obj.create()
  File "/usr/local/lib/python3.10/site-packages/gradio/helpers.py", line 298, in create
    client_utils.synchronize_async(self.cache)
  File "/usr/local/lib/python3.10/site-packages/gradio_client/utils.py", line 889, in synchronize_async
    return fsspec.asyn.sync(fsspec.asyn.get_loop(), func, *args, **kwargs)  # type: ignore
  File "/usr/local/lib/python3.10/site-packages/fsspec/asyn.py", line 103, in sync
    raise return_result
  File "/usr/local/lib/python3.10/site-packages/fsspec/asyn.py", line 56, in _runner
    result[0] = await coro
  File "/usr/local/lib/python3.10/site-packages/gradio/helpers.py", line 360, in cache
    prediction = await Context.root_block.process_api(
  File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1695, in process_api
    result = await self.call_function(
  File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1235, in call_function
    prediction = await anyio.to_thread.run_sync(
  File "/usr/local/lib/python3.10/site-packages/anyio/to_thread.py", line 56, in run_sync
    return await get_async_backend().run_sync_in_worker_thread(
  File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 2144, in run_sync_in_worker_thread
    return await future
  File "/usr/local/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 851, in run
    result = context.run(func, *args)
  File "/usr/local/lib/python3.10/site-packages/gradio/utils.py", line 692, in wrapper
    response = f(*args, **kwargs)
  File "/home/user/app/app.py", line 24, in detect_objects
    model = YOLO(model_path)
  File "/usr/local/lib/python3.10/site-packages/ultralyticsplus/ultralytics_utils.py", line 65, in __init__
    raise NotImplementedError(
NotImplementedError: Unable to load model='MvitHYF/v8mvitcocoaseed2024'. As an example try model='yolov8n.pt' or model='yolov8n.yaml'

I also ran app.py on VSCode, and everything ran perfectly (run on localhost). However, I encountered this error when trying to create the space. I tried adding yolov8n.pt to both the model and the space site, but nothing changed. At first, I thought it might fix the error.
Thank you for you help


I downloaded one of the pretrained yolo models from the link:
https://github.com/WongKinYiu/yolov7/releases
In this case, yolov7-tiny.pt is downloaded.
Then tried to run the code to load the model and convert it to onnx file:
import torch
import onnx

model = torch.load('./yolo_custom/yolov7-tiny.pt')
input_shape = (1, 3, 640, 640)
torch.onnx.export(model, torch.randn(input_shape), 'yolov7-tiny.onnx', opset_version=11)

An error occurs on
model = torch.load('./yolo_custom/yolov7-tiny.pt')

and the error message is:
ModuleNotFoundError: No module named 'models'

The issue is reproducible even on Colab. Is there anything wrong on the steps?


# Veri kümenizin yolunu ayarlayın
data_dir = '/content/datasets/u-granada-g-detect-2'

# Sınıf etiketlerini yükleyin
class_names = ['knife', 'gun']

# Eğitim ve doğrulama veri kümelerini oluşturun
train_images = []
train_targets = []
val_images = []
val_targets = []

for phase in ['train', 'valid']:
    image_dir = os.path.join(data_dir, phase, 'images')
    label_dir = os.path.join(data_dir, phase, 'labels')

    for image_path in tqdm(os.listdir(image_dir)):
        image = cv2.imread(os.path.join(image_dir, image_path))
        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

        label_path = os.path.join(label_dir, image_path.replace('.jpg', '.txt'))
        with open(label_path, 'r') as f:
            labels = []
            for line in f:
                bbox = [float(x) for x in line.split()]
                labels.append([int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]), 1 if bbox[4] == 0 else 0])

        train_images.append(image)
        train_targets.append(labels)

        if phase == 'val':
            val_images.append(image)
            val_targets.append(labels)

# Yeniden boyutlandırma işlemi
resized_train_images = [cv2.resize(img, (224, 224)) for img in train_images]
resized_val_images = [cv2.resize(img, (224, 224)) for img in val_images]

# NumPy dizisine dönüştürme
train_images = np.array(resized_train_images)
val_images = np.array(resized_val_images)

# Normalleştirme işlemi
train_images = train_images / 255.0
val_images = val_images / 255.0

# EfficientNet B4 modelini yükleyin
efficientnet = EfficientNet.from_name('efficientnet-b4')

# YOLOv8n modelini oluşturun
yolo_model = model.YOLOv8(cfg='yolov8x.yaml')

# Modeli EfficientNet B4 omurgası ile değiştirin
yolo_model.model.backbone = efficientnet

# Eğitim ve doğrulama veri kümelerini ayarlayın
train_dataset = torch.utils.data.Dataset(train_images, train_targets)
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=16, shuffle=True)
val_dataset = torch.utils.data.Dataset(val_images, val_targets)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=16, shuffle=False)

# Eğitim ayarlarını belirleyin
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(yolo_model.parameters(), lr=0.001)

# Modeli eğitin
for epoch in range(100):
    # Her epoch için eğitim ve doğrulama aşamaları
    for images, targets in tqdm(train_loader):
        images = images.to(device)
        targets = [target.to(device) for target in targets]

        # Tahminleri hesaplayın ve kaybı hesaplayın
        outputs = yolo_model(images)
        loss = criterion(outputs[0], targets[0])

        # Geri yayılım ve parametreleri güncelleyin
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    # Doğrulama setinde performansı değerlendirin
    with torch.no_grad():
        total_correct = 0
        total_samples = 0
        for images, targets in tqdm(val_loader):
            images = images.to(device)
        targets = [target.to(device) for target in targets]

        # Tahminleri hesaplayın
        outputs = yolo_model(images)
        predictions = torch.argmax(outputs[0], dim=1)

        # Doğru tahminleri sayın
        for i, (prediction, target) in enumerate(zip(predictions, targets)):
            total_samples += 1
            if prediction == target:
                total_correct += 1

        # Doğrulama doğruluğunu hesaplayın
        accuracy = total_correct / total_samples
        print(f'Epoch {epoch + 1}: Val Accuracy: {accuracy:.4f}')

# Eğitim tamamlandıktan sonra modeli kaydedin
torch.save(yolo_model, 'yolov8_knife_gun_detector.pth')

print('Model successfully trained and saved!')

How can i fix this error?
AttributeError                            Traceback (most recent call last)
<ipython-input-19-500f42116361> in <cell line: 5>()
      3
      4 # YOLOv8n modelini oluşturun
----> 5 yolo_model = model.YOLOv8(cfg='yolov8x.yaml')
      6
      7 # Modeli EfficientNet B4 omurgası ile değiştirin

/usr/local/lib/python3.10/dist-packages/torch/nn/modules/module.py in __getattr__(self, name)
   1686             if name in modules:
   1687                 return modules[name]
-> 1688         raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
   1689
   1690     def __setattr__(self, name: str, value: Union[Tensor, 'Module']) -> None:

AttributeError: 'YOLO' object has no attribute 'YOLOv8'


I work with YOLO8
My task is to determine the contours of the cars (that is, display them as rectangles), then make a count (for counting: the contour must cross the middle of the frame
for two lanes of different traffic: oncoming and passing
And at the end, count the total number of cars
Loop and request the next frame each time and work should be done with it separately
At the moment, I'm trying to draw the contours, but there's nothing on the video.
In the output, I get something like this:
`0: 384x640 27 cars, 1 truck, 1 tv, 93.0ms
Speed: 1.9ms preprocess, 93.0ms inference, 0.4ms postprocess per image at shape (1, 3, 384, 640)
0: 384x640 26 cars, 2 trucks, 88.1ms
Speed: 1.7ms preprocess, 88.1ms inference, 0.5ms postprocess per image at shape (1, 3, 384, 640)
0: 384x640 26 cars, 2 trucks, 104.2ms
Speed: 1.5ms preprocess, 104.2ms inference, 0.6ms postprocess per image at shape (1, 3, 384, 640)`
My code:
import cv2
from ultralytics import YOLO

model = YOLO('yolov8s.pt')

video_path = 'output2.avi'
video = cv2.VideoCapture(video_path)

if not video.isOpened():
    print("Ошибка: Не удается открыть видео.")
    exit()

current_frame = 0

while True:
    ret, frame = video.read()
    if not ret:
        break

    current_frame += 1

    results = model(frame)

    car_results = [detection for detection in results if detection[-1] in [2, 5, 7]]

    for result in car_results:
        x1, y1, x2, y2, confidence, class_id = result.xyxy[0]
        x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 255), 2)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()

I have tried various ways to fix the problem, but all attempts are unsuccessful


i want to use default YOLOv8 model (yolov8m.pt) for object detection. I know that default YOLO models uses COCO dataset and can detect 80+ objects. I just want to detect like 5 of them, how can i achieve this?


When I try to train my model by executing the code cell below:
python train.py --img-size 2048 --cfg cfg/training/yolov7.yaml --hyp data/road_sign_data.yaml --batch 8 --epochs 100 --data data/road_sign.yaml --weights yolov7_training.pt --workers 24 --name yolo_road_det
I have the following error message :
Traceback (most recent call last):
File "C:\Users\531558\Documents\streamline2\yolov7\train.py", line 12, in
import torch.distributed as dist
File "C:\Users\531558\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\torch_init_.py", line 141, in
raise err
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\531558\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\torch\lib\shm.dll" or one of its dependencies.
It looks like it can not import torch.distibuted
I tried to change the version of python I am using (from 3.12 to 3.11.9) but it still does not work. I also tried many other way to do the training of a yolov7 model but none of them were working... If you have any solution it would be very helpful


I'm encountering an issue with my YOLO model.
Initially, I trained it with 7 classes. Now, I want to add 4 new classes to the model. However, when I combine the data for the original 7 classes with the new 4 classes, the training time and associated cloud costs significantly increase. What's a good solution to efficiently incorporate these additional classes into the model without inflating training time and costs?
My expecting is reduce the cost and training time in incremental learnng.


i trained a model yolov8 with custom dataset containing 26 classess, but when i convert the model to tflite i noticed that  it gives as output [1,30,8400] and this is what caused me errors when using my model with flutter.
the error
E/AndroidRuntime(18479): Caused by: java.lang.IllegalArgumentException: Cannot copy from a TensorFlowLite tensor (Identity) with shape [1, 30, 8400] to a Java object with shape [1, 26].
how can i modify the output shape of my model ?
this is how trained my model :
 from ultralytics import YOLO

 model = YOLO('yolov8s.pt')

 results = model.train(data='/kaggle/input/my-
 dataset/my_dataset/data.yaml', epochs=100, imgsz=640)

and this is the content of file the data.yaml
train: /kaggle/input/dataset-asl/ASL/train/images
val: /kaggle/input/dataset-asl/ASL/valid/images

nc: 26
names: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z']

and this is how convert my model to format tflite  :
from ultralytics import YOLO

# Load a model
model = YOLO('best.pt')

# Export the model
model.export(format='tflite')

and this is output after convert :
Ultralytics YOLOv8.2.4  Python-3.9.0 torch-2.2.1+cpu CPU (Intel
Core(TM) i5-7300U 2.60GHz)
Model summary (fused): 168 layers, 3010718 parameters, 0
gradients, 8.1 GFLOPs

PyTorch: starting from 'best.pt' with input shape (1, 3, 640, 640)
BCHW and output shape(s) (1, 30, 8400) (6.0 MB)

TensorFlow SavedModel: starting export with tensorflow 2.15.0...
WARNING  tensorflow<=2.13.1 is required, but tensorflow==2.15.0 is
currently installed
https://github.com/ultralytics/ultralytics/issues/5161

ONNX: starting export with onnx 1.15.0 opset 17...
ONNX: simplifying with onnxsim 0.4.36...
ONNX: export success  1.8s, saved as 'best.onnx' (11.7 MB)
TensorFlow SavedModel: starting TFLite export with onnx2tf
1.17.5...
TensorFlow SavedModel: export success  14.3s, saved as
'best_saved_model' (29.5 MB)

TensorFlow Lite: starting export with tensorflow 2.15.0...
TensorFlow Lite: export success  0.0s, saved as
'best_saved_model\best_float32.tflite' (11.7 MB)

Export complete (16.8s)
Results saved to C:\Users\Bachir\Desktop\api\tflite
Predict:         yolo predict task=detect
model=best_saved_model\best_float32.tflite imgsz=640
Validate:        yolo val task=detect
model=best_saved_model\best_float32.tflite imgsz=640
data=/kaggle/input/my-dataset/my_dataset/data.yaml
Visualize:       https://netron.app
'best_saved_model\\best_float32.tflite'
emphasized text


I've trained a YOLOV8 model to identify objects in an intersection (ie cars, roads etc).
It is working OK and I can get the output as an image with the objects of interested segmented.
However, what I need to do is to capture the raw geometries (polygons) so I can save them on a txt file later on.
I tried what Ive found in the documentation (https://docs.ultralytics.com/modes/predict/#key-features-of-predict-mode) however the returning object is not the same as the documentation says.
In fact, the result is a list of tensorflow numbers:

Here's my code:
import argparse
import cv2
import numpy as np
from pathlib import Path
from ultralytics.yolo.engine.model import YOLO

# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument('--source', type=str, required=True, help='Source image directory or file')
parser.add_argument('--output', type=str, default='output', help='Output directory')
args = parser.parse_args()

# Create output directory if it doesn't exist
Path(args.output).mkdir(parents=True, exist_ok=True)

# Model path
model_path = r'C:\\_Projects\\best_100img.pt'

# Load your model directly
model = YOLO(model_path)
model.fuse()

# Load image(s)
if Path(args.source).is_dir():
    image_paths = list(Path(args.source).rglob('*.tiff'))
else:
    image_paths = [args.source]

# Process each image
for image_path in image_paths:
    img = cv2.imread(str(image_path))
    if img is None:
        continue

    # Perform inference
    predictions = model.predict(image_path, save=True, save_txt=True)

print("Processing complete.")

Here's the problem: the return object (predictions variable) has no boxes, masks, keypoints and etc.
I guess my questions are:

Why the result is so different from the documentation?
Is there a conversion step?


I trained a YOLO-V8 instance segmentation model to segment an object with class label 0. I used the CLI to instantiate the trained model and predict on the test data.
!yolo task=segment mode=predict model='/weights/best.pt' conf=0.25 source='/test/images' imgsz=1024 save=True save_txt=True save_conf=True

After prediction, the label files gets stored in .txt format. These label files contain the class index followed by the polygonal coordinates and finally the confidence score of the bounding box predictions. But, bounding box coordinates, that is, x-center, y-center, width, height are not included in the label file. I would also like to include these bounding box coordinates to each of the labels file since I would like to use these bounding box coordinates later for post-processing. A sample label file content looks like this:
0 0.21582 0.0898438 0.214844 0.0908203 0.213867 0.0908203 0.210938 0.09375 0.210938 0.0947266 0.203125 0.102539 0.203125 0.103516 0.201172 0.105469 0.200195 0.105469 0.199219 0.106445 0.199219 0.113281 0.200195 0.114258 0.200195 0.115234 0.203125 0.115234 0.204102 0.116211 0.223633 0.116211 0.224609 0.117188 0.227539 0.117188 0.228516 0.118164 0.230469 0.118164 0.231445 0.119141 0.234375 0.119141 0.235352 0.120117 0.248047 0.120117 0.249023 0.121094 0.251953 0.121094 0.25293 0.12207 0.254883 0.0927734 0.260742 0.0917969 0.256836 0.0917969 0.255859 0.0908203 0.233398 0.0908203 0.232422 0.0898438 0.910849

I am not saving the predictions to any 'result' variable here and I am running the predictions only in the CLI.