mteb/FreshStackRetrieval huggingface dataset:
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 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?
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.