From 2173c37238d632a6f6dcd202c212d749f767263c Mon Sep 17 00:00:00 2001 From: MatthewNoyce <131261051+MatthewNoyce@users.noreply.github.com> Date: Wed, 18 Sep 2024 10:53:33 +0100 Subject: [PATCH] `ultralytics 8.2.96` new `results[0].to_df` Pandas, XML and CSV methods (#16267) Co-authored-by: UltralyticsAssistant Co-authored-by: Ultralytics Assistant <135830346+UltralyticsAssistant@users.noreply.github.com> Co-authored-by: Glenn Jocher --- docs/en/hub/inference-api.md | 4 +- tests/test_python.py | 5 +- ultralytics/__init__.py | 2 +- ultralytics/engine/results.py | 86 ++++++++++++++++++++++++++++++++++- 4 files changed, 92 insertions(+), 5 deletions(-) diff --git a/docs/en/hub/inference-api.md b/docs/en/hub/inference-api.md index cd98347ef..bc569ac73 100644 --- a/docs/en/hub/inference-api.md +++ b/docs/en/hub/inference-api.md @@ -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" diff --git a/tests/test_python.py b/tests/test_python.py index b5dd0c883..55f087f00 100644 --- a/tests/test_python.py +++ b/tests/test_python.py @@ -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 diff --git a/ultralytics/__init__.py b/ultralytics/__init__.py index 9f6607772..d5140b155 100644 --- a/ultralytics/__init__.py +++ b/ultralytics/__init__.py @@ -1,6 +1,6 @@ # Ultralytics YOLO 🚀, AGPL-3.0 license -__version__ = "8.2.95" +__version__ = "8.2.96" import os diff --git a/ultralytics/engine/results.py b/ultralytics/engine/results.py index 89b2d5c8e..57cc4b04b 100644 --- a/ultralytics/engine/results.py +++ b/ultralytics/engine/results.py @@ -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 '\n' 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: