guides/distance-calculation/ #7956
Replies: 40 comments 119 replies
-
Hi, I'm clicking on the objects to track distance. But it's not working. Why? |
Beta Was this translation helpful? Give feedback.
-
Hi, I am actually using mss to detect objs from my screen so how can i implement the distance caluclations as there are about 10 objects and their distance must be mapped for every obj with every other obj ? |
Beta Was this translation helpful? Give feedback.
-
Hi @pderrenger. The mouse clicking feature distance calculation ain't working for me. I'm clicking the mouse but no response. I'm using windows 11. Code: from ultralytics import YOLO model = YOLO("yolov8n.pt") cap = cv2.VideoCapture("file.mp4") Video writervideo_writer = cv2.VideoWriter("MyFile.avi", Init distance-calculation objdist_obj = distance_calculation.DistanceCalculation() while cap.isOpened():
cap.release() Please help. |
Beta Was this translation helpful? Give feedback.
-
How to find the distance of the objects from the camera? For example, in your test video, how to calculate the distance of each person from the camera? Would be glad to have a solution. TIA. |
Beta Was this translation helpful? Give feedback.
-
#I am trying to find the distance between the object and camera in real-time object detection using my webcam on yolov8n.pt model. but I am getting this error: Traceback (most recent call last): Process finished with exit code 1 #Would be glad to have a solution. TIA. from ultralytics.solutions import distance_calculation
import cv2
import argparse
from ultralytics import YOLO
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="YOLOv8 live")
parser.add_argument(
"--webcam-resolution",
default=[1280, 720],
nargs=2,
type=int
)
args = parser.parse_args()
return args
# Load the model
model = YOLO("yolov8n.pt")
# Initialize the video capture
args = parse_arguments()
frame_width, frame_height = args.webcam_resolution
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)
assert cap.isOpened(), "Error opening video file"
# Initialize distance calculation object
dist_obj = distance_calculation.DistanceCalculation()
# Process video frames
while True:
success, frame = cap.read()
if not success:
break
# Run object tracking
tracks = model.track(frame, persist=True)
# Calculate distances and update the frame
frame = dist_obj.start_process(frame, tracks)
print(frame.shape)
# Display the frame
cv2.imshow('Distance Calculation', frame)
if cv2.waitKey(1) == ord('q'): # Press 'q' to quit
break
# Release resources
cap.release()
cv2.destroyAllWindows() |
Beta Was this translation helpful? Give feedback.
-
Hi, I wanted to measure distance of vehicles using a camera, but the camera's POV is inside the car (example: dashcam). So, I wanna ask if we are able to measure distance automatically without needing to click on the bounding boxes. Thanks . |
Beta Was this translation helpful? Give feedback.
-
Hello, I am running this code, the code works perfectly, however the measurement made in real time is not correct, how can I improve this problem? from ultralytics import YOLO model = YOLO("yolov8m.pt") Use 0 for the default webcamcap = cv2.VideoCapture(1) #Init distance-calculation obj while cap.isOpened(): cap.release() |
Beta Was this translation helpful? Give feedback.
-
Hello, I am running this code, the code works perfectly; I mean, the code can detect de object and it gets a measure. However the measurement made in real time is not correct, how can I improve this problem? from ultralytics import YOLO model = YOLO("yolov8m.pt") Use 0 for the default webcamcap = cv2.VideoCapture(1) #Init distance-calculation obj while cap.isOpened(): cap.release() |
Beta Was this translation helpful? Give feedback.
-
Hi, I already calibrated my camera to measure the correct distance between objects with the camera at a distance of 1.75 cm. However, when I move the camera away and measure the distance between the objects again, the measurement is incorrect. How can I improve this measurement by moving the camera away and maintaining the correct distance? |
Beta Was this translation helpful? Give feedback.
-
Hey, I'm unable the interact with the objects in my .avi file. Does this work on Ubuntu 20.04.6 LTS? My python version is 3.11.8. The code is running and it's detecting objects from my mp4 file, but I'm unable to interact with distance_calculation.avi. I don't get any popup window while running the code file. Code file from ultralytics import YOLO model = YOLO("yolov8m.pt") cap = cv2.VideoCapture("/home/abdullah/Desktop/intern depth map/depthultra/car.mp4") Video writervideo_writer = cv2.VideoWriter("distance_calculation.avi", Init distance-calculation objdist_obj = distance_calculation.DistanceCalculation() while cap.isOpened():
cap.release() |
Beta Was this translation helpful? Give feedback.
-
can we use google colab to rrun the program and draw the lines? |
Beta Was this translation helpful? Give feedback.
-
hi i am trying to measure the distance of potholes from a car camera. can you provide the full code to measure the distance between the camera and the potholes in a video file |
Beta Was this translation helpful? Give feedback.
-
Hi, when running the following code: from ultralytics import YOLO Use 0 for the default webcamcap = cv2.VideoCapture(1) I get the following in my terminal: However, I would like to disappear all that and only have in the terminal the distance between the two selected objects. How can I do this? |
Beta Was this translation helpful? Give feedback.
-
whenever i try to run any version of this code i get an error message that there's no module called ultralytics.solutions despite having downloaded ultralytics using pip install. TIA!! |
Beta Was this translation helpful? Give feedback.
-
how can I use this in images with normal bounding boxes, how can I use it that way? |
Beta Was this translation helpful? Give feedback.
-
Traceback (most recent call last):
File "C:\Users\lenovo\Desktop\ultralytics-main\ultralytics.egg-info\ripeness_demo.py", line 27, in <module>
cls_id = result.cls # Get the class ID
File "C:\Users\lenovo\Desktop\ultralytics-main\ultralytics\utils\__init__.py", line 160, in __getattr__
raise AttributeError(f"'{name}' object has no attribute '{attr}'. See valid attributes below.\n{self.__doc__}")
AttributeError: 'Results' object has no attribute 'cls'. See valid attributes below.
在 2024-04-16 08:44:57,"Paula Derrenger" ***@***.***> 写道:
Hello Paula,
Thanks for reaching out and sharing the specifics of your classes! 🌱 Based on your class names 'low', 'mid', and 'high', I suggest a minor adjustment to the provided example to reflect your class names accurately. Here's how you can customize the output to display the maturity stage according to your classification:
fromultralyticsimportYOLOmodel=YOLO("path/to/your/model.pt") # Load your trained modelsuccess, img=cap.read() # Assuming 'cap' is your cv2.VideoCapture objectresults=model.predict(img) # Run prediction on the imageforresultinresults:
cls_id=result.cls# Get the class IDmaturity=model.model.names[cls_id] # Get the maturity stage name: 'low', 'mid', or 'high'print(f"Tomato maturity stage: {maturity}")
Remember to replace "path/to/your/model.pt" with the actual path to your trained model. This snippet will correctly interpret the class IDs as 'low', 'mid', and 'high', matching your setup.
If you have any further questions or need additional assistance, feel free to reach out again. Happy coding! 🚀
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
import cv2
import numpy as np
from ultralytics import YOLO # 确保正确导入了YOLOv8
# 加载模型
model = YOLO("C:/Users/lenovo/Desktop/ultralytics-main/runs/detect/train_ripeness/weights/best.pt") # 替换为你的模型路径
# 读取图像
image = cv2.imread("C:/Users/lenovo/Desktop/ultralytics-main/ultralytics/cfg/datasets/demo_images_ripeness/images/val/5.jpg")
# 进行预测
results = model.predict(image)
# 初始化类别计数
counts = {'low_ripeness': 0, 'mid_ripeness': 0, 'high_ripeness': 0}
# 遍历预测结果
for xyxy, conf, cls in zip(results.xyxy[0], results.conf[0], results.cls[0]):
x1, y1, x2, y2 = map(int, xyxy)
category = model.names[cls] # 获取类别名称
confidence = conf # 获取置信度
# 计算红色占比 (这部分代码可能需要调整以匹配你的实际需求)
tomato_region = image[y1:y2, x1:x2]
hsv = cv2.cvtColor(tomato_region, cv2.COLOR_BGR2HSV)
lower_red = np.array([0, 50, 50])
upper_red = np.array([10, 255, 255])
mask = cv2.inRange(hsv, lower_red, upper_red)
red_ratio = cv2.countNonZero(mask) / (x2 - x1) * (y2 - y1)
# 根据红色占比计算成熟度百分比 (这里需要定义具体的映射逻辑)
maturity_percent = int(red_ratio * 100)
# 更新类别计数 (这里假设每个检测到的对象都对应一个成熟度类别)
counts[category] += 1
# 显示边界框、类别和成熟度百分比
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, f"{category}: {maturity_percent}%", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# 显示类别计数
for i, (category, count) in enumerate(counts.items()):
cv2.putText(image, f"{category}: {count}", (10, 30 + 20 * i), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
# 显示图像
cv2.imshow("Tomato Ripeness Detection", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
"Error during execution: Traceback (most recent call last):
File "C:\Users\lenovo\Desktop\ultralytics-main\ultralytics.egg-info\count&ripeness.py", line 18, in <module>
for xyxy, conf, cls in zip(results.xyxy[0], results.conf[0], results.cls[0]):
AttributeError: 'list' object has no attribute 'xyxy'"
At 2024-04-16 08:31:05, "Glenn Jocher" ***@***.***> wrote:
Hey there!
Absolutely, here's a streamlined code snippet based on the guidelines:
fromultralyticsimportYOLO# Load your custom tomato maturity modelmodel=YOLO("path/to/your/tomato-model.pt")
# Load your imageimg=cv2.imread("path/to/your/image.jpg") # Just as an example# Perform predictionresults=model.predict(img)
# Loop through detected tomatoes and print their maturity stagesforresultinresults:
maturity=model.names[result.cls] # Get the maturity stage nameprint(f"Tomato maturity stage: {maturity}")
# Optionally visualize resultsresults.show()
This assumes you've got the appropriate model and an image ready to go. The model.predict part handles identifying tomatoes and their maturity stages, while results.show() directly visualizes those annotations on the image for you. 🍅✨
Hope this helps and happy coding! If there's anything more you need, just shout out.
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
from ultralytics.yolo.engine.predictor import BasePredictor
from ultralytics.yolo.engine.results import Results
from ultralytics.yolo.utils import DEFAULT_CFG, LOGGER, SETTINGS, callbacks, ops
from ultralytics.yolo.utils.plotting import Annotator, colors, save_one_box
from ultralytics.yolo.utils.torch_utils import smart_inference_mode
from ultralytics.yolo.utils.files import increment_path
from ultralytics.yolo.utils.checks import check_imshow
from ultralytics.yolo.cfg import get_cfg
error:
ModuleNotFoundError: No module named 'ultralytics.yolo'
在 2024-04-16 09:01:14,"Paula Derrenger" ***@***.***> 写道:
@Yh11001 hi Paula! 🌟
Absolutely, glad to help! Your approach to integrating the maturity stage of tomatoes into the visual output is spot-on. Just ensure your model is trained to recognize these stages accurately, and your snippet will do the job beautifully.
For a more tailored response or additional queries, feel free to reach out. Keep up the great work, and I'm here for any further assistance you might need. Happy coding! 🚀
Also, do check out our guide on Distance Calculation using Ultralytics YOLOv8. It might add an interesting dimension to your project by measuring distances between detected tomatoes or other objects in the frame! 🍅✨
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you were mentioned.Message ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
Is there any method to calculate the distance of every object with respect to camera |
Beta Was this translation helpful? Give feedback.
-
How do I calculate distances between two objects from multiple images/pictures(jpg file). not video |
Beta Was this translation helpful? Give feedback.
-
Hi, |
Beta Was this translation helpful? Give feedback.
-
Hi, How's the distance being measured? In my case, the distance is way off unfortunately. Is it possible to optimize the measurement when knowing the size of some of the detected objects? Like on a sports court for example, where the size of a penalty box is known or the size of a basket, maybe even the size of the ball. |
Beta Was this translation helpful? Give feedback.
-
i am getting version incompatibility issue, please tell your python version |
Beta Was this translation helpful? Give feedback.
-
Hello, first of all I am definitely thankful for all your continuous support and help. I am currently stuck in my bachelor project hoping I could use some help. I am creating an abandoned bags detection system so that it detects a person carrying his bag and if he drops it or leave it behind then this bag's class is defined as abandoned object and if the same person comes back to get his bag this class is changed back to normal, I am thinking about using that distance calculation so that if the bag is away from the person for a certain threshold then it is abandoned. but I am stuck in the code hoping for some help. Thanks in advance :) |
Beta Was this translation helpful? Give feedback.
-
You've set the pixel per meter to 10 in this. Could you tell me how you found out the pixel per meter? In a real-time scenario, there could be different cameras, so for accurate results, the pixel per meter should also be accurate. I'm awaiting your response |
Beta Was this translation helpful? Give feedback.
-
how is this "Conversion factor from pixels to meters" working? |
Beta Was this translation helpful? Give feedback.
-
is it gonna integrate with object detection by YOLO v8 both together showing the bounding boxes with Distance and type of the objects? |
Beta Was this translation helpful? Give feedback.
-
How can I adapt the code from above to work with an instance segmentation model? I am detecting railroad lines, so the bounding boxes are not very accurate a lot of the time, and I want to use the masks from my segmentation model to calculate my distances. Here is my code: model = YOLO("YOLOv8-pretrained-200-epochs.pt") cap = cv2.VideoCapture("IMG_2688.MOV") Video writervideo_writer = cv2.VideoWriter("distance_calculation.avi", cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h)) Init distance-calculation objdist_obj = solutions.DistanceCalculation(names=names, view_img=True) while cap.isOpened():
cap.release() |
Beta Was this translation helpful? Give feedback.
-
I am trying to calculate the distance from each detected object to the vertical center of the screen so I can compare how far each of them are from the center. I would prefer to do this using the masks because I have an instance segmentation model, but I can do it with bounding boxes too. How can I figure out how far the centroids of each box or mask are from the center? For example, if my image is 640 pixels wide and 320 pixels tall, I want the center of the 640. |
Beta Was this translation helpful? Give feedback.
-
Hi, I am very new to deep learning, and I'm trying to build a model from YOLOv8 with transfer learning to estimate the speed and calculate the distance of vehicles in a given data set. Although the ultralytics documentation is quite robust, I am still determining how to code them together. I want to train my model on the custom data set, and finally, from the measured distance and speed, I want to calculate the time to collision. So, I would appreciate any help from the community; thanks! By the way, I am working with a dataset consisting of temporally nearby frames. |
Beta Was this translation helpful? Give feedback.
-
guides/distance-calculation/
Distance Calculation Using Ultralytics YOLOv8
https://docs.ultralytics.com/guides/distance-calculation/
Beta Was this translation helpful? Give feedback.
All reactions