Created
January 4, 2023 07:52
-
-
Save realphongha/2a4b7675474c8bbe0061ed64806852ad to your computer and use it in GitHub Desktop.
Draw bounding boxes on image
This file contains 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 cv2 | |
def bbox_percentage_to_pixel(bbox, h, w): | |
x1, y1, x2, y2 = bbox | |
return x1 * w, y1 * h, x2 * w, y2 * h | |
def draw_bboxes_on_image(img, bboxes, show=True, percentage=True): | |
h, w = img.shape[:2] | |
for raw_bbox in bboxes: | |
bbox = raw_bbox[:4] | |
cls = None | |
if len(raw_bbox) > 4: | |
cls = str(raw_bbox[4]) | |
x1, y1, x2, y2 = (bbox_percentage_to_pixel(bbox, h, w) if percentage else bbox) | |
img = cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), | |
(255, 0, 0), 2) | |
if cls is not None: | |
img = cv2.putText(img, cls, (int(x1), int(y1)), | |
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, | |
cv2.LINE_AA) | |
if show: | |
cv2.imshow("Image", img) | |
cv2.waitKey() | |
return img | |
if __name__ == "__main__": | |
img = "image.jpg" | |
bboxes = [ | |
[0.0019206365, 0.027576663, 0.35729018, 0.9271332, 1], | |
[0.83108604, 0.17452964, 0.941884, 0.35912782, 4] | |
] | |
img = cv2.imread(img) | |
draw_bboxes_on_image(img, bboxes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment