generated from roboflow/template-python
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New function [CSVSink] - allowing to serialise Detections to a CSV file #818
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
SkalskiP
merged 14 commits into
roboflow:develop
from
AdonaiVera:allowing_serialise_detections_csv
Feb 2, 2024
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
5e339f9
[CSVSink] - allowing to serialise Detections to a CSV file ready for …
AdonaiVera 1256833
Applied feedback from SkalskiP in PR #818
AdonaiVera fd00bd4
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] 4ec353f
Apply format
AdonaiVera 91260bd
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] 788bc31
Improvements in thread #818: documentation, handle unit test, improve…
AdonaiVera aba5c0a
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] e899b42
Fix length of the line
AdonaiVera b1034fe
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] ac6f3d6
small docs updates
SkalskiP abb8daa
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] d6ee644
final tests
SkalskiP 2e76c66
Merge remote-tracking branch 'origin/allowing_serialise_detections_cs…
SkalskiP 6bebd4e
fix(pre_commit): 🎨 auto format pre-commit hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
--- | ||
comments: true | ||
status: new | ||
--- | ||
|
||
# Save Detections | ||
|
||
<div class="md-typeset"> | ||
<h2>CSV Sink</h2> | ||
</div> | ||
|
||
:::supervision.detection.tools.csv_sink.CSVSink |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,181 @@ | ||
from __future__ import annotations | ||
|
||
import csv | ||
import os | ||
from typing import Any, Dict, List, Optional | ||
|
||
from supervision.detection.core import Detections | ||
|
||
BASE_HEADER = [ | ||
"x_min", | ||
"y_min", | ||
"x_max", | ||
"y_max", | ||
"class_id", | ||
"confidence", | ||
"tracker_id", | ||
] | ||
|
||
|
||
class CSVSink: | ||
""" | ||
A utility class for saving detection data to a CSV file. This class is designed to | ||
efficiently serialize detection objects into a CSV format, allowing for the | ||
inclusion of bounding box coordinates and additional attributes like `confidence`, | ||
`class_id`, and `tracker_id`. | ||
|
||
!!! tip | ||
|
||
CSVSink allow to pass custom data alongside the detection fields, providing | ||
flexibility for logging various types of information. | ||
|
||
Args: | ||
file_name (str): The name of the CSV file where the detections will be stored. | ||
Defaults to 'output.csv'. | ||
|
||
Example: | ||
```python | ||
import supervision as sv | ||
from ultralytics import YOLO | ||
|
||
model = YOLO(<SOURCE_MODEL_PATH>) | ||
csv_sink = sv.CSVSink(<RESULT_CSV_FILE_PATH>) | ||
frames_generator = sv.get_video_frames_generator(<SOURCE_VIDEO_PATH>) | ||
|
||
with csv_sink: | ||
for frame in frames_generator: | ||
result = model(frame)[0] | ||
detections = sv.Detections.from_ultralytics(result) | ||
sink.append(detections, custom_data={'<CUSTOM_LABEL>':'<CUSTOM_DATA>'}) | ||
``` | ||
""" # noqa: E501 // docs | ||
|
||
def __init__(self, file_name: str = "output.csv") -> None: | ||
""" | ||
Initialize the CSVSink instance. | ||
|
||
Args: | ||
file_name (str): The name of the CSV file. | ||
|
||
Returns: | ||
None | ||
""" | ||
self.file_name = file_name | ||
self.file: Optional[open] = None | ||
self.writer: Optional[csv.writer] = None | ||
self.header_written = False | ||
self.field_names = [] | ||
|
||
def __enter__(self) -> CSVSink: | ||
self.open() | ||
return self | ||
|
||
def __exit__( | ||
self, | ||
exc_type: Optional[type], | ||
exc_val: Optional[Exception], | ||
exc_tb: Optional[Any], | ||
) -> None: | ||
self.close() | ||
|
||
def open(self) -> None: | ||
""" | ||
Open the CSV file for writing. | ||
|
||
Returns: | ||
None | ||
""" | ||
parent_directory = os.path.dirname(self.file_name) | ||
if parent_directory and not os.path.exists(parent_directory): | ||
os.makedirs(parent_directory) | ||
|
||
self.file = open(self.file_name, "w", newline="") | ||
self.writer = csv.writer(self.file) | ||
|
||
def close(self) -> None: | ||
""" | ||
Close the CSV file. | ||
|
||
Returns: | ||
None | ||
""" | ||
if self.file: | ||
self.file.close() | ||
|
||
@staticmethod | ||
def parse_detection_data( | ||
detections: Detections, custom_data: Dict[str, Any] = None | ||
) -> List[Dict[str, Any]]: | ||
parsed_rows = [] | ||
for i in range(len(detections.xyxy)): | ||
row = { | ||
"x_min": detections.xyxy[i][0], | ||
"y_min": detections.xyxy[i][1], | ||
"x_max": detections.xyxy[i][2], | ||
"y_max": detections.xyxy[i][3], | ||
"class_id": "" | ||
if detections.class_id is None | ||
else str(detections.class_id[i]), | ||
"confidence": "" | ||
if detections.confidence is None | ||
else str(detections.confidence[i]), | ||
"tracker_id": "" | ||
if detections.tracker_id is None | ||
else str(detections.tracker_id[i]), | ||
} | ||
|
||
if hasattr(detections, "data"): | ||
for key, value in detections.data.items(): | ||
if value.ndim == 0: | ||
row[key] = value | ||
else: | ||
row[key] = value[i] | ||
|
||
if custom_data: | ||
row.update(custom_data) | ||
parsed_rows.append(row) | ||
return parsed_rows | ||
|
||
def append( | ||
AdonaiVera marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self, detections: Detections, custom_data: Dict[str, Any] = None | ||
) -> None: | ||
""" | ||
Append detection data to the CSV file. | ||
|
||
Args: | ||
detections (Detections): The detection data. | ||
custom_data (Dict[str, Any]): Custom data to include. | ||
|
||
Returns: | ||
None | ||
""" | ||
if not self.writer: | ||
raise Exception( | ||
f"Cannot append to CSV: The file '{self.file_name}' is not open." | ||
) | ||
field_names = CSVSink.parse_field_names(detections, custom_data) | ||
if not self.header_written: | ||
self.field_names = field_names | ||
self.writer.writerow(field_names) | ||
self.header_written = True | ||
|
||
if field_names != self.field_names: | ||
print( | ||
f"Field names do not match the header. " | ||
f"Expected: {self.field_names}, given: {field_names}" | ||
) | ||
|
||
parsed_rows = CSVSink.parse_detection_data(detections, custom_data) | ||
for row in parsed_rows: | ||
self.writer.writerow( | ||
[row.get(field_name, "") for field_name in self.field_names] | ||
) | ||
|
||
@staticmethod | ||
def parse_field_names( | ||
detections: Detections, custom_data: Dict[str, Any] | ||
) -> List[str]: | ||
dynamic_header = sorted( | ||
set(custom_data.keys()) | set(getattr(detections, "data", {}).keys()) | ||
) | ||
return BASE_HEADER + dynamic_header |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.