`ultralytics 8.2.96` new `results[0].to_df` Pandas, XML and CSV methods (#16267)

Co-authored-by: UltralyticsAssistant <web@ultralytics.com>
Co-authored-by: Ultralytics Assistant <135830346+UltralyticsAssistant@users.noreply.github.com>
Co-authored-by: Glenn Jocher <glenn.jocher@ultralytics.com>
pull/16338/head^2 v8.2.96
MatthewNoyce 1 day ago committed by GitHub
parent 225e6e2b25
commit 2173c37238
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 4
      docs/en/hub/inference-api.md
  2. 5
      tests/test_python.py
  3. 2
      ultralytics/__init__.py
  4. 86
      ultralytics/engine/results.py

@ -139,7 +139,7 @@ The [Ultralytics HUB](https://www.ultralytics.com/hub) Inference API returns a J
results = model("image.jpg")
# Print image.jpg results in JSON format
print(results[0].tojson())
print(results[0].to_json())
```
=== "cURL"
@ -219,7 +219,7 @@ The [Ultralytics HUB](https://www.ultralytics.com/hub) Inference API returns a J
results = model("image.jpg")
# Print image.jpg results in JSON format
print(results[0].tojson())
print(results[0].to_json())
```
=== "cURL"

@ -269,7 +269,10 @@ def test_results(model):
r = r.to(device="cpu", dtype=torch.float32)
r.save_txt(txt_file=TMP / "runs/tests/label.txt", save_conf=True)
r.save_crop(save_dir=TMP / "runs/tests/crops/")
r.tojson(normalize=True)
r.to_json(normalize=True)
r.to_df(decimals=3)
r.to_csv()
r.to_xml()
r.plot(pil=True)
r.plot(conf=True, boxes=True)
print(r, len(r), r.path) # print after methods

@ -1,6 +1,6 @@
# Ultralytics YOLO 🚀, AGPL-3.0 license
__version__ = "8.2.95"
__version__ = "8.2.96"
import os

@ -14,6 +14,7 @@ import torch
from ultralytics.data.augment import LetterBox
from ultralytics.utils import LOGGER, SimpleClass, ops
from ultralytics.utils.checks import check_requirements
from ultralytics.utils.plotting import Annotator, colors, save_one_box
from ultralytics.utils.torch_utils import smart_inference_mode
@ -818,7 +819,90 @@ class Results(SimpleClass):
return results
def to_df(self, normalize=False, decimals=5):
"""
Converts detection results to a Pandas Dataframe.
This method converts the detection results into Pandas Dataframe format. It includes information
about detected objects such as bounding boxes, class names, confidence scores, and optionally
segmentation masks and keypoints.
Args:
normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
decimals (int): Number of decimal places to round the output values to. Defaults to 5.
Returns:
(DataFrame): A Pandas Dataframe containing all the information in results in an organized way.
Examples:
>>> results = model("path/to/image.jpg")
>>> df_result = results[0].to_df()
>>> print(df_result)
"""
import pandas as pd
return pd.DataFrame(self.summary(normalize=normalize, decimals=decimals))
def to_csv(self, normalize=False, decimals=5, *args, **kwargs):
"""
Converts detection results to a CSV format.
This method serializes the detection results into a CSV format. It includes information
about detected objects such as bounding boxes, class names, confidence scores, and optionally
segmentation masks and keypoints.
Args:
normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
decimals (int): Number of decimal places to round the output values to. Defaults to 5.
*args (Any): Variable length argument list to be passed to pandas.DataFrame.to_csv().
**kwargs (Any): Arbitrary keyword arguments to be passed to pandas.DataFrame.to_csv().
Returns:
(str): CSV containing all the information in results in an organized way.
Examples:
>>> results = model("path/to/image.jpg")
>>> csv_result = results[0].to_csv()
>>> print(csv_result)
"""
return self.to_df(normalize=normalize, decimals=decimals).to_csv(*args, **kwargs)
def to_xml(self, normalize=False, decimals=5, *args, **kwargs):
"""
Converts detection results to XML format.
This method serializes the detection results into an XML format. It includes information
about detected objects such as bounding boxes, class names, confidence scores, and optionally
segmentation masks and keypoints.
Args:
normalize (bool): Whether to normalize the bounding box coordinates by the image dimensions.
If True, coordinates will be returned as float values between 0 and 1. Defaults to False.
decimals (int): Number of decimal places to round the output values to. Defaults to 5.
*args (Any): Variable length argument list to be passed to pandas.DataFrame.to_xml().
**kwargs (Any): Arbitrary keyword arguments to be passed to pandas.DataFrame.to_xml().
Returns:
(str): An XML string containing all the information in results in an organized way.
Examples:
>>> results = model("path/to/image.jpg")
>>> xml_result = results[0].to_xml()
>>> print(xml_result)
"""
check_requirements("lxml")
df = self.to_df(normalize=normalize, decimals=decimals)
return '<?xml version="1.0" encoding="utf-8"?>\n<root></root>' if df.empty else df.to_xml(*args, **kwargs)
def tojson(self, normalize=False, decimals=5):
"""Deprecated version of to_json()."""
LOGGER.warning("WARNING ⚠ 'result.tojson()' is deprecated, replace with 'result.to_json()'.")
return self.to_json(normalize, decimals)
def to_json(self, normalize=False, decimals=5):
"""
Converts detection results to JSON format.
@ -836,7 +920,7 @@ class Results(SimpleClass):
Examples:
>>> results = model("path/to/image.jpg")
>>> json_result = results[0].tojson()
>>> json_result = results[0].to_json()
>>> print(json_result)
Notes:

Loading…
Cancel
Save