Closed MuhammadBilal848 closed 4 days ago
π Hello @MuhammadBilal848, thank you for reaching out and using YOLOv5 π! This is an automated response, and an Ultralytics engineer will assist you soon.
It seems you're encountering an AttributeError
because the input to the model should be a NumPy array or a preprocessed image rather than a string. Let's update your code to fix this issue.
You should read the image using a library like OpenCV to convert it into an array before passing it to the model. Here's how you can update your code:
import torch
import cv2
# Load the model
model = torch.hub.load('.', 'custom', path='best_seg.pt', source='local')
# Read image
img = cv2.imread('res.jpg')
# Ensure the image is in the correct format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Run inference
results = model(img)
# Print results
print(results)
'res.jpg'
is in the correct directory or provide the full path.cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
part ensures that the image is in the RGB format, which is standard for most pre-trained models.To help us provide you with the best assistance, consider including:
For more details on using YOLOv5, you can check out our Tutorials. If you're interested in our latest updates, consider trying out YOLOv8!
Weβre excited to help you resolve this issue, and appreciate your patience while our team gets back to you. π
The error is resolved! The following code is used to resolve this.
import torch
import matplotlib.pyplot as plt
import numpy as np
import cv2
from torchvision.transforms import functional as F
# model = torch.hub.load('/home/user/Downloads/YOLOv5/yolov5', 'custom', path='best_seg.pt', source='local') # this also works
model = torch.hub.load('.', 'custom', path='best_seg.pt', source='local')
image = cv2.imread('res.jpg') # Read image with OpenCV
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Convert BGR to RGB
image = F.to_tensor(image) # Convert to PyTorch tensor
image = image.unsqueeze(0) # Add batch dimension
results = model(image)
print(results)
@MuhammadBilal848 great to hear the issue is resolved! If you have any more questions or need further assistance, feel free to ask.
Search before asking
YOLOv5 Component
Other
Bug
I trained a YOLOv5 custom segmentation model and tried inferencing it without CLI using the following code.
Error:
Environment
No response
Minimal Reproducible Example
No response
Additional
No response
Are you willing to submit a PR?