Created
January 3, 2025 02:39
-
-
Save visionNoob/a63eb9f1031174caa260aa144a66659c to your computer and use it in GitHub Desktop.
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
import ultralytics | |
from ultralytics import YOLO | |
import matplotlib.pyplot as plt | |
import cv2 | |
import numpy as np | |
print(ultralytics.__version__) | |
def crop_obb(image, obb): | |
""" Crop the Oriented Bounding Box (OBB) """ | |
x_c, y_c, w, h, angle = obb | |
center = (x_c, y_c) | |
size = (w, h) | |
angle_deg = np.degrees(angle) | |
# Rotated rectangle | |
rot_rect = ((x_c, y_c), (w, h), angle_deg) | |
# Get the rotation matrix | |
box = cv2.boxPoints(rot_rect) | |
box = np.int0(box) | |
# Crop the bounding box region | |
width = int(w) | |
height = int(h) | |
src_pts = box.astype("float32") | |
dst_pts = np.array([[0, height-1], | |
[0, 0], | |
[width-1, 0], | |
[width-1, height-1]], dtype="float32") | |
M = cv2.getPerspectiveTransform(src_pts, dst_pts) | |
cropped_img = cv2.warpPerspective(image, M, (width, height)) | |
return cropped_img | |
model = YOLO("yolo11n-obb.pt") | |
results = model("https://ultralytics.com/images/boats.jpg") # predict on an image | |
results[0].show() # display the image | |
cropped_img = crop_obb(results[0].orig_img, results[0].obb.xywhr[0].cpu().numpy()) | |
plt.imshow(cropped_img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment