from ultralytics import YOLO
import cv2
def detect_and_visualize_objects_yolov8(image_path, model, confidence_threshold=0.5):
image = cv2.imread(image_path)
results = model(image)
boxes = []
confidences = []
for result in results:
for box in result.boxes:
if box.conf > confidence_threshold:
# Extract bounding box coordinates
--> x1, y1, x2, y2 = box.xyxy[0].item(), box.xyxy[1].item(), box.xyxy[2].item(), box.xyxy[3].item()
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
w = x2 - x1
h = y2 - y1
boxes.append([x1, y1, w, h])
confidences.append(float(box.conf))
# Draw bounding box
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
label = f'{box.cls} {box.conf:.2f}'
cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
# Calculate the total area of the detected objects
total_area = sum(w * h for _, _, w, h in boxes)
# Display the image with bounding boxes
cv2.imshow('Detected Objects', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
return total_area
# Load YOLOv8 model
model = YOLO('yolov8n.pt')
# Usage
image_path = 'data.jpg'
total_area = detect_and_visualize_objects_yolov8(image_path, model)
print(f'Total area of detected objects: {total_area}')
I have issues with extracting the boundary box coordinates. My goal here is to make a piece of code to extract the sum of area for the objects detected when inferencing the yolov8 model. Running the above code results in this error, “RuntimeError: a Tensor with 4 elements cannot be converted to Scalar”. Here is the picture… Please help me to solve this. And if theres any other issues from the code, please do not hesitate to write your recommended fix and suggestions. Thanks!
Ming Xian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.