add crop and pad util

action-recog2
fcakyon 5 months ago
parent 8ae655a724
commit 5d51d79113
  1. 4
      docs/en/reference/utils/__init__.md
  2. 23
      ultralytics/utils/__init__.py

@ -177,4 +177,8 @@ keywords: Ultralytics, utils, TQDM, Python, ML, Machine Learning utilities, YOLO
## ::: ultralytics.utils.vscode_msg
<br><br><hr><br>
## ::: ultralytics.utils.crop_and_pad
<br><br>

@ -1258,6 +1258,29 @@ def vscode_msg(ext="ultralytics.ultralytics-snippets") -> str:
return "" if installed else f"{colorstr('VS Code:')} view Ultralytics VS Code Extension ⚡ at {url}"
def crop_and_pad(frame, box, margin_percent):
"""Crop box with margin and take square crop from frame."""
x1, y1, x2, y2 = map(int, box)
w, h = x2 - x1, y2 - y1
# Add margin
margin_x, margin_y = int(w * margin_percent / 100), int(h * margin_percent / 100)
x1, y1 = max(0, x1 - margin_x), max(0, y1 - margin_y)
x2, y2 = min(frame.shape[1], x2 + margin_x), min(frame.shape[0], y2 + margin_y)
# Take square crop from frame
size = max(y2 - y1, x2 - x1)
center_y, center_x = (y1 + y2) // 2, (x1 + x2) // 2
half_size = size // 2
square_crop = frame[
max(0, center_y - half_size) : min(frame.shape[0], center_y + half_size),
max(0, center_x - half_size) : min(frame.shape[1], center_x + half_size),
]
return cv2.resize(square_crop, (224, 224), interpolation=cv2.INTER_LINEAR)
# Run below code on utils init ------------------------------------------------------------------------------------
# Check first-install steps

Loading…
Cancel
Save