Skip to content

⚡️ Speed up function process_transformers_detection_result by 223% #51

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 18 additions & 8 deletions supervision/detection/tools/transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,17 @@ def process_transformers_detection_result(
dict: Processed detection result including bounding boxes, confidence scores,
class IDs, and data.
"""
class_ids = detection_result["labels"].cpu().detach().numpy().astype(int)
data = append_class_names_to_data(class_ids, id2label, {})
# Convert all relevant tensors once
labels = detection_result["labels"].detach().cpu().numpy().astype(int)
boxes = detection_result["boxes"].detach().cpu().numpy()
scores = detection_result["scores"].detach().cpu().numpy()

data = append_class_names_to_data(labels, id2label, {})

return dict(
xyxy=detection_result["boxes"].cpu().detach().numpy(),
confidence=detection_result["scores"].cpu().detach().numpy(),
class_id=class_ids,
xyxy=boxes,
confidence=scores,
class_id=labels,
data=data,
)

Expand Down Expand Up @@ -241,7 +245,13 @@ def append_class_names_to_data(
data = {}

if id2label is not None:
class_names = np.array([id2label[class_id] for class_id in class_ids])
data[CLASS_NAME_DATA_FIELD] = class_names

# Use a lookup table to vectorize the mapping if possible.
# Create an array of appropriate size where indices correspond to class IDs.
max_key = max(id2label.keys())
lookup = np.empty(max_key + 1, dtype=object)
for key, name in id2label.items():
lookup[key] = name
# Use the lookup array for vectorized mapping. This assumes the IDs in class_ids
# do not exceed max_key.
data[CLASS_NAME_DATA_FIELD] = lookup[class_ids]
return data