Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify Inference Results Print Output #11488

Closed
1 task done
jmurel opened this issue May 4, 2023 · 9 comments
Closed
1 task done

Modify Inference Results Print Output #11488

jmurel opened this issue May 4, 2023 · 9 comments
Labels
question Further information is requested Stale

Comments

@jmurel
Copy link

jmurel commented May 4, 2023

Search before asking

Question

I have a custom-trained model I am currently inferring on several hundred images in a given directory. This is my command:

import torch

# Download YOLOv5 from PyTorch Hub
model = torch.hub.load('ultralytics/yolov5', 'custom', path='/path/to/custom/model')

IMG_DIR = 'path/to/image/directory'
FILE_NAMES = ['file1', 'file2', 'file3', etc.]

# A batch of images
imgs = [IMG_DIR + file_name for file_name in FILE_NAMES]

# Inference
results = model(imgs)

# Save the results
results.save()
results.print()

This command/script itself works fine; at the moment, there are no issues. Per 'results.print()', it returns the following:

image 1/30: 3177x2517 1 marginalia
image 2/30: 3177x2517 3 marginalias
image 3/30: 3177x2517 (no detections)
image 4/30: 3177x2517 3 marginalias
image 5/30: 3177x2517 3 marginalias
image 6/30: 3177x2517 1 marginalia
image 7/30: 3177x2517 2 marginalias
image 8/30: 3177x2517 2 marginalias
image 9/30: 3177x2517 4 marginalias
image 10/30: 3177x2517 1 marginalia
[...]

My question is how to modify the output from results.print(). There are two modifications in which I am interested:

  1. How might I also have the image file names included in the printed output, e.g.:
image 1/30: newsystemoranaly02brya_0050.jp2 3177x2517 1 annotation
image 2/30: newsystemoranaly02brya_0051.jp2 3177x2517 3 annotations
[...]
  1. I am also interested in seeing how many of the images within the image set the model identified has having a given object. So, for example, if I inferred the model on the above ten images, it would print (in addition to the above output) something along the lines of "9/10 images with marginalia." I know image classification tools can do this task, but since I have labeled my dataset for object detection for other purposes, I wanted to inquire how readily I may modify/append YOLOv5's results.print() output.

Any information you can provide is appreciated!

Additional

No response

@jmurel jmurel added the question Further information is requested label May 4, 2023
@github-actions
Copy link
Contributor

github-actions bot commented May 4, 2023

👋 Hello @jmurel, 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 a minimum reproducible example to help us debug it.

If this is a custom training ❓ Question, please provide as much information as possible, including dataset image examples and training logs, and verify you are following our Tips for Best Training Results.

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

YOLOv5 CI

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

Introducing YOLOv8 🚀

We're excited to announce the launch of our latest state-of-the-art (SOTA) object detection model for 2023 - YOLOv8 🚀!

Designed to be fast, accurate, and easy to use, YOLOv8 is an ideal choice for a wide range of object detection, image segmentation and image classification tasks. With YOLOv8, you'll be able to quickly and accurately detect objects in real-time, streamline your workflows, and achieve new levels of accuracy in your projects.

Check out our YOLOv8 Docs for details and get started with:

pip install ultralytics

@glenn-jocher
Copy link
Member

@jmurel hello!

  1. To include the image file names in the printed output, you can modify the "results.print()" line to the following:

    for i, fname in enumerate(FILE_NAMES):
        print(f'image {i}/{len(FILE_NAMES)}: {fname} {results.imgs[i].shape[1]}x{results.imgs[i].shape[0]} {len(results.pred[i])} annotation(s)')
    

    This will print the image name, the dimensions of the image, and the number of annotations/detections on the image.

  2. If you'd like to also print out how many of the images within the image set the model identified as having a certain object, you can add code to count the number of detections that contain the desired class label. For example:

    label = 'marginalia'
    count = 0
    for i, pred in enumerate(results.pred):
        for det in pred:
            if det[-1] == label:
                count += 1
                break
    print(f'{count}/{len(FILE_NAMES)} images with {label}')
    

    This will go through each image's detections and count how many times the label 'marginalia' appears in the detections. It will then print out the count and the total number of images.

Hope this helps!

@jmurel
Copy link
Author

jmurel commented May 5, 2023

@glenn-jocher Thank you very much for your help!

I needed to modify the first script a bit, as it returned some errors, but it worked after the modification. In case anyone else here is interested, I'm including the modified script snippet below:

for i, fname in enumerate(FILE_NAMES):
    print(f'image {i+1}/{len(FILE_NAMES)}: {fname} {results.ims[i].shape[1]}x{results.ims[i].shape[0]} {len(results.pred[i])} annotation(s)')

The second script, however, has left me more perplexed. It works w/out terminal errors, but the script seems to be miscounting (or at least misprinting). For example, when running the model on a small test thirteen-image set, it prints the following results:

image 1/13: newsystemoranaly02brya_0000.jp2 2912x4368 0 annotation(s)
image 2/13: newsystemoranaly02brya_0001.jp2 2559x3333 0 annotation(s)
image 3/13: newsystemoranaly02brya_0002.jp2 2517x3177 1 annotation(s)
image 4/13: newsystemoranaly02brya_0003.jp2 2517x3177 0 annotation(s)
image 5/13: newsystemoranaly02brya_0004.jp2 2517x3177 0 annotation(s)
image 6/13: newsystemoranaly02brya_0005.jp2 2517x3177 0 annotation(s)
image 7/13: newsystemoranaly02brya_0006.jp2 2517x3177 0 annotation(s)
image 8/13: newsystemoranaly02brya_0007.jp2 2517x3177 0 annotation(s)
image 9/13: newsystemoranaly02brya_0008.jp2 2517x3177 0 annotation(s)
image 10/13: newsystemoranaly02brya_0009.jp2 2517x3177 0 annotation(s)
image 11/13: newsystemoranaly02brya_0010.jp2 2517x3177 0 annotation(s)
image 12/13: newsystemoranaly02brya_0011.jp2 2517x3177 0 annotation(s)
image 13/13: newsystemoranaly02brya_0012.jp2 2517x3177 0 annotation(s)
0/13 images with marginalia

Although the model has identified one image as containing the object (i.e. marginalia), the script reports 0 images. I've tried toying a bit with the script excerpt provided by @glenn-jocher but nothing has worked yet. I thought I would leave a comment in case they or anyone else has thoughts on what the issue may be.

@glenn-jocher
Copy link
Member

@jmurel, thank you for the update and glad that the modified script snippet worked for you.

Regarding the second script, it seems like the issue might be due to the fact that you're looking for a specific label ('marginalia') within the detections, but the label might not be exactly the same as what you're looking for.

Here's a modified version of the snippet that should work:

label = 'marginalia'
count = 0
for i, pred in enumerate(results.pred):
    for det in pred:
        if det[-1].startswith(label):  # check if the label starts with 'marginalia'
            count += 1
            break
print(f'{count}/{len(FILE_NAMES)} images with {label}')

This modified version checks if the detected label starts with 'marginalia' (using .startswith()), so it should capture variations of the label such as 'marginalias', 'marginali', etc.

Hopefully this helps! Let me know if there are still any issues.

@jmurel
Copy link
Author

jmurel commented May 8, 2023

@glenn-jocher Thank you for this!
Unfortunately the modified version returns an error still, albeit different:

Traceback (most recent call last):
  File "/home/jmurel/Documents/object_detection_scripts/yolov5_deploy.py", line 25, in <module>
    if det[-1].startswith(label):  # check if the label starts with 'marginalia'
AttributeError: 'Tensor' object has no attribute 'startswith'

I've tried looking around online, bu can't find much on how to resolve this. Might you have any suggestions to point me in the right direction?

@glenn-jocher
Copy link
Member

@jmurel Sorry for the confusion - it looks like the detections are actually tensors, not strings, so we can't use string methods like .startswith().

Instead, we can convert the label to a tensor and use PyTorch methods to perform the check. Here's the modified snippet:

import torch

label = 'marginalia'
count = 0
label_tensor = torch.tensor([LABEL_NAMES.index(label)]).cuda()  # convert label to tensor and move to GPU
for i, pred in enumerate(results.pred):
    pred_tensor = torch.tensor(pred).cuda()
    if (pred_tensor[:, -1] == label_tensor).any():  # check if any detection in the tensor has label
        count += 1
print(f'{count}/{len(FILE_NAMES)} images with {label}')

This snippet first converts the label to a tensor (label_tensor) and moves it to the GPU. Then for each image's detections, it converts the list of detections to a tensor (pred_tensor) and checks if any of the detection labels match label_tensor. If a match is found, the count is incremented.

Note that this snippet assumes that LABEL_NAMES is a list of the label names in the same order as the model's output, and that the model output's last column contains the predicted label indices. If LABEL_NAMES is missing or contains different names or orders, the above code will need to be modified accordingly.

@jmurel
Copy link
Author

jmurel commented May 11, 2023

@glenn-jocher When I run this script, it returns:

Traceback (most recent call last):
  File "/home/jmurel/Documents/object_detection_scripts/yolov5_deploy.py", line 22, in <module>
    label_tensor = torch.tensor([FILE_NAMES.index(label)]).cuda()  # convert label to tensor and move to GPU
ValueError: 'marginalia' is not in list

I've been trying to troubleshoot, but can't seem to get it right. Do you have any thoughts?

@glenn-jocher
Copy link
Member

@jmurel hello,

It looks like the error is being caused because the label ('marginalia') is not found in the FILE_NAMES list.

However, the label should actually be found in the LABEL_NAMES list, which is the list of class names for the model's output. To fix this issue, you can replace FILE_NAMES.index(label) with LABEL_NAMES.index(label), like so:

import torch

label = 'marginalia'
count = 0
label_tensor = torch.tensor([LABEL_NAMES.index(label)]).cuda()  # convert label to tensor and move to GPU
for i, pred in enumerate(results.pred):
    pred_tensor = torch.tensor(pred).cuda()
    if (pred_tensor[:, -1] == label_tensor).any():  # check if any detection in the tensor has label
        count += 1
print(f'{count}/{len(FILE_NAMES)} images with {label}')

This should allow the script to run without errors. Let me know if you have any further questions or issues!

@github-actions
Copy link
Contributor

👋 Hello there! We wanted to give you a friendly reminder that this issue has not had any recent activity and may be closed soon, but don't worry - you can always reopen it if needed. If you still have any questions or concerns, please feel free to let us know how we can help.

For additional resources and information, please see the links below:

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 YOLO 🚀 and Vision AI ⭐

@github-actions github-actions bot added the Stale label Jun 11, 2023
@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Jun 22, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested Stale
Projects
None yet
Development

No branches or pull requests

2 participants