Calculating Object Distance from the Camera using Ultralytics YOLO v8 #14086
Replies: 1 comment
-
@Najiullah-khan hi there! 👋 Thank you for reaching out with your query on calculating object distance from the camera using Ultralytics YOLOv8. To achieve this, you can leverage the bounding box centroids and a known reference object size to estimate distances. Here's a structured approach to guide you:
Here's an example code snippet to help you get started: import cv2
from ultralytics import YOLO
# Load the YOLO model
model = YOLO("yolov8n.pt")
# Load an image
image_path = r"C:\Users\PMYLS\Downloads\WhatsApp Image 2024-06-26 at 00.13.09_83ea1ef8.jpg"
image = cv2.imread(image_path)
# Perform inference
results = model(image)
# Known width of the object (e.g., a car width in meters)
KNOWN_WIDTH = 1.8 # Example width in meters
# Focal length of the camera (calibrated)
FOCAL_LENGTH = 800 # Example focal length in pixels
# Iterate through the results and calculate distances
for r in results:
for box in r.boxes:
cls = box.cls
conf = box.conf
if conf >= 0.5:
# Calculate the width of the bounding box in pixels
box_width = box.xyxy[2] - box.xyxy[0]
# Calculate the distance
distance = (KNOWN_WIDTH * FOCAL_LENGTH) / box_width
print(f"Object: {model.names[int(cls)]}, Distance: {distance:.2f} meters")
# Display the image with bounding boxes and distances
for r in results:
r.plot()
cv2.imshow("Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows() Additional ResourcesFor more detailed guidance, you can refer to our Distance Calculation Guide. If you encounter any issues, please ensure you are using the latest version of the Ultralytics YOLO package. If the problem persists, providing a minimum reproducible example will help us assist you better. You can find more information on creating one here. Feel free to reach out if you have any more questions. Happy coding! 😊 |
Beta Was this translation helpful? Give feedback.
-
I'm working on a project where I need to calculate the distance of objects from the camera using image using Ultralytics YOLO. I'm looking for guidance on the best approach to achieve this.
from ultralytics import YOLO
import cv2
Step 4: Load an image (replace 'path/to/image.jpg' with the actual image path)
image_path = r"C:\Users\PMYLS\Downloads\WhatsApp Image 2024-06-26 at 00.13.09_83ea1ef8.jpg"
image = cv2.imread(image_path)
Step 5: Perform inference
results = model(image)
Step 6: Initialize an empty list to store the predicted class names
names_array = []
names = model.names
Step 7: Iterate through the results and filter by confidence threshold
for r in results:
for box in r.boxes:
cls = box.cls
conf = box.conf
# Append the class name if confidence is >= 0.4
if conf >= 0.5:
names_array.append(names[int(cls)])
Print the predicted class names
print("Predicted class names:", names_array)
Beta Was this translation helpful? Give feedback.
All reactions