ultralytics / yolov5

YOLOv5 🚀 in PyTorch > ONNX > CoreML > TFLite
https://docs.ultralytics.com
GNU Affero General Public License v3.0
51.04k stars 16.41k forks source link

Second stage classifier for character detection #9233

Closed EKebriaei closed 2 years ago

EKebriaei commented 2 years ago

Search before asking

Question

Hi guys. I trained two different models. The first for plate detection (number of classes: 1) and the second for character detection (number of classes: 28). I use apply_classifier method for second stage classifier. I changed the detect.py line 129 to:

# Second-stage classifier (optional)
classifier_model = DetectMultiBackend('my_weight.pt', device=device)
pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

I get the following error:

/content/yolov5/utils/general.py:993: UserWarning: Creating a tensor from a list of numpy.ndarrays is extremely slow. Please consider converting the list to a single numpy.ndarray with numpy.array() before converting to a tensor. (Triggered internally at  ../torch/csrc/utils/tensor_new.cpp:201.)
  pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1)  # classifier prediction
Traceback (most recent call last):
  File "detect.py", line 255, in <module>
    main(opt)
  File "detect.py", line 250, in main
    run(**vars(opt))
  File "/usr/local/lib/python3.7/dist-packages/torch/autograd/grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "detect.py", line 130, in run
    pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
  File "/content/yolov5/utils/general.py", line 994, in apply_classifier
    x[i] = x[i][pred_cls1 == pred_cls2]  # retain matching class detections
IndexError: The shape of the mask [1, 34] at index 1 does not match the shape of the indexed tensor [1, 6] at index 1

Additional

This is the apply classifier method:

def apply_classifier(x, model, img, im0):
    # applies a second stage classifier to yolo outputs
    im0 = [im0] if isinstance(im0, np.ndarray) else im0
    for i, d in enumerate(x):  # per image
        if d is not None and len(d):
            d = d.clone()
            # Reshape and pad cutouts
            b = xyxy2xywh(d[:, :4])  # boxes
            b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1)  # rectangle to square
            b[:, 2:] = b[:, 2:] * 1.3 + 30  # pad
            d[:, :4] = xywh2xyxy(b).long()

            # Rescale boxes from img_size to im0 size
            scale_coords(img.shape[2:], d[:, :4], im0[i].shape)

            # Classes
            pred_cls1 = d[:, 5].long()
            ims = []
            for j, a in enumerate(d):  # per item
                cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
                im = cv2.resize(cutout, (224, 224))  # BGR
                # cv2.imwrite('test%i.jpg' % j, cutout)

                im = im[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x416
                im = np.ascontiguousarray(im, dtype=np.float32)  # uint8 to float32
                im /= 255.0  # 0 - 255 to 0.0 - 1.0
                ims.append(im)

            pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1)  # classifier prediction
            x[i] = x[i][pred_cls1 == pred_cls2]  # retain matching class detections

    return x
github-actions[bot] commented 2 years ago

👋 Hello @EKebriaei, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ Tutorials to get started, where you can find quickstart guides for simple tasks like Custom Data Training all the way to advanced concepts like Hyperparameter Evolution.

If this is a 🐛 Bug Report, please provide screenshots and minimum viable code to reproduce your issue, otherwise we can not help you.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online W&B logging if available.

For business inquiries or professional support requests please visit https://ultralytics.com or email support@ultralytics.com.

Requirements

Python>=3.7.0 with all requirements.txt installed including PyTorch>=1.7. To get started:

git clone https://github.com/ultralytics/yolov5  # clone
cd yolov5
pip install -r requirements.txt  # install

Environments

YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):

Status

CI CPU testing

If this badge is green, all YOLOv5 GitHub Actions Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training (train.py), validation (val.py), inference (detect.py) and export (export.py) on macOS, Windows, and Ubuntu every 24 hours and on every commit.

glenn-jocher commented 2 years ago

@EKebriaei the second stage classifier in detect.py must have the same exact classes as the detection model, it filters every detection through the classifier to reduce FPs.

EKebriaei commented 2 years ago

@glenn-jocher Thanks for the quick response. Actually I trained a YOLOv5 model to detect license plate (one class) and another YOLO5 model to detect character from license (28 classes). I wanted to do plate detection and character detection in an end-to-end manner. Is that apply_classifier method works for here? Or should I train a model to detect both of them in a single training task. Plate detection dataset contains car images and location of plate in those images. Character detection dataset contains plate images and location of each character inside those images. Being real time as well as high accuracy is important to me. I would be thankful if anyone can help me.

github-actions[bot] commented 2 years ago

👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.

Access additional YOLOv5 🚀 resources:

Access additional Ultralytics ⚡ resources:

Feel free to inform us of any other issues you discover or feature requests that come to mind in the future. Pull Requests (PRs) are also always welcomed!

Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!

glenn-jocher commented 1 year ago

@EKebriaei Great to hear about your project! For an end-to-end solution with high accuracy and real-time performance, training a single YOLOv5 model to detect both the license plate and characters in a single task would be the most efficient approach. This way, the model can detect both the plate and characters simultaneously in a single inference step, providing faster and more streamlined results. You can combine the datasets and have the model learn to detect both objects and characters simultaneously. Let me know if you have any further questions or need assistance with the combined training process!

lylsalt commented 7 months ago

I would like to ask if the two-stage target recognition problem mentioned above has been resolved. I have encountered difficulties in coding.

error: Fusing layers... YOLOv5m summary: 212 layers, 20901426 parameters, 0 gradients, 48.0 GFLOPs <class 'models.yolo.DetectionModel'> Traceback (most recent call last): File "/home/featurize/work/yolov5-7.0(s car)/detect.py", line 280, in main(opt) File "/home/featurize/work/yolov5-7.0(s car)/detect.py", line 275, in main run(*vars(opt)) File "/environment/miniconda3/lib/python3.10/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context return func(args, **kwargs) File "/home/featurize/work/yolov5-7.0(s car)/detect.py", line 154, in run pred = utils.general.apply_classifier(pred, classifier_model, im, im0s) File "/home/featurize/work/yolov5-7.0(s car)/utils/general.py", line 1128, in apply_classifier pred_cls2 = output.argmax(1) AttributeError: 'list' object has no attribute 'argmax'

glenn-jocher commented 7 months ago

Hey there! It seems like you're getting an AttributeError because output is a list and doesn't have the argmax method. This typically occurs if the model's output structure doesn't match what the apply_classifier function expects. To resolve this, ensure that output is a PyTorch tensor before you attempt to call .argmax(1) on it. If output is indeed intended to be a tensor but is somehow a list, look into how output is generated within your classifier model's forward pass. A quick workaround, if output is a list of tensors (one tensor per image), you might need to concatenate them along the correct axis before calling .argmax(1). Here's an example:

if isinstance(output, list):
    output = torch.cat(output, dim=0)
pred_cls2 = output.argmax(1)

Please let me know if this helps or if you're facing any other issues! 😊