# 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.