Args: im (np.ndarray): a BGR image in range [0,255]. It will not be modified. boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. labels: (list[str] or None) color: a 3-tuple BGR color (in range [0, 255]) Returns: np.nd
(im, boxes, labels=None, color=None)
| 380 | |
| 381 | |
| 382 | def draw_boxes(im, boxes, labels=None, color=None): |
| 383 | """ |
| 384 | Args: |
| 385 | im (np.ndarray): a BGR image in range [0,255]. It will not be modified. |
| 386 | boxes (np.ndarray): a numpy array of shape Nx4 where each row is [x1, y1, x2, y2]. |
| 387 | labels: (list[str] or None) |
| 388 | color: a 3-tuple BGR color (in range [0, 255]) |
| 389 | |
| 390 | Returns: |
| 391 | np.ndarray: a new image. |
| 392 | """ |
| 393 | boxes = np.asarray(boxes, dtype='int32') |
| 394 | if labels is not None: |
| 395 | assert len(labels) == len(boxes), "{} != {}".format(len(labels), len(boxes)) |
| 396 | areas = (boxes[:, 2] - boxes[:, 0] + 1) * (boxes[:, 3] - boxes[:, 1] + 1) |
| 397 | sorted_inds = np.argsort(-areas) # draw large ones first |
| 398 | assert areas.min() > 0, areas.min() |
| 399 | # allow equal, because we are not very strict about rounding error here |
| 400 | assert boxes[:, 0].min() >= 0 and boxes[:, 1].min() >= 0 \ |
| 401 | and boxes[:, 2].max() <= im.shape[1] and boxes[:, 3].max() <= im.shape[0], \ |
| 402 | "Image shape: {}\n Boxes:\n{}".format(str(im.shape), str(boxes)) |
| 403 | |
| 404 | im = im.copy() |
| 405 | if color is None: |
| 406 | color = (15, 128, 15) |
| 407 | if im.ndim == 2 or (im.ndim == 3 and im.shape[2] == 1): |
| 408 | im = cv2.cvtColor(im, cv2.COLOR_GRAY2BGR) |
| 409 | for i in sorted_inds: |
| 410 | box = boxes[i, :] |
| 411 | if labels is not None: |
| 412 | im = draw_text(im, (box[0], box[1]), labels[i], color=color) |
| 413 | cv2.rectangle(im, (box[0], box[1]), (box[2], box[3]), |
| 414 | color=color, thickness=1) |
| 415 | return im |
| 416 | |
| 417 | |
| 418 | try: |