Distance Measurement Issues with OpenCV and ‘Logitech C920 HD Pro Webcam
Using OpenCV, I tried to measure the distance of objects from the camera but never succeeded; it always gave inaccurate and unrelated results. Is there a way to achieve this correctly? I’ve read and applied numerous online resources, but the results remain incorrect.
import torch
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont
model = torch.hub.load('ultralytics/yolov5', 'custom', path='çalışan/best.pt', force_reload=True)
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Kamera açılamadı!")
exit()
while True:
ret, frame = cap.read()
if not ret:
print("Kare okunamadı!")
break
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
results = model(img)
detections = results.xyxy[0].numpy()
draw = ImageDraw.Draw(img)
for detection in detections:
x1, y1, x2, y2, conf, cls = detection
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
draw.rectangle([(x1, y1), (x2, y2)], outline="red", width=2)
center_x = (x1 + x2) // 2
center_y = (y1 + y2) // 2
crosshair_size = 10
draw.line([(center_x - crosshair_size, center_y), (center_x + crosshair_size, center_y)], fill="red", width=2)
draw.line([(center_x, center_y - crosshair_size), (center_x, center_y + crosshair_size)], fill="red", width=2)
img_width, img_height = img.size
screen_center_x = img_width // 2
screen_center_y = img_height // 2
crosshair_size = 20
draw.line([(screen_center_x - crosshair_size, screen_center_y), (screen_center_x + crosshair_size, screen_center_y)], fill="blue", width=2)
draw.line([(screen_center_x, screen_center_y - crosshair_size), (screen_center_x, screen_center_y + crosshair_size)], fill="blue", width=2)
frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
cv2.imshow('YOLOv5 Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I’ve tried every formula and written every code I found online, even asked ChatGPT, but still couldn’t find a solution. All I wanted was to measure the distance of detected objects to the camera.
Serkan Çelen is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.