Skip to content
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

Set line width and label font size proportional to image size #9

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@

Fork from https://github.com/nalepae/bounding-box/tree/master. I've set the line width and label size proportional to the image size. Helpfull for large images. I've opened a pull request to the original repo, but it appears to be non-active. Hence I'll use my own fork. Original documentation below.


# Bounding Box
**Bounding Box** is a library to plot pretty bounding boxes with a simple Python API.

Expand Down
18 changes: 11 additions & 7 deletions bounding_box/bounding_box.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,15 @@
_DEFAULT_COLOR_NAME = "green"

_FONT_PATH = _os.path.join(_LOC, "Ubuntu-B.ttf")
_FONT_HEIGHT = 15
_FONT = ImageFont.truetype(_FONT_PATH, _FONT_HEIGHT)

def _rgb_to_bgr(color):
return list(reversed(color))

def _color_image(image, font_color, background_color):
return background_color + (font_color - background_color) * image / 255

def _get_label_image(text, font_color_tuple_bgr, background_color_tuple_bgr):
text_image = _FONT.getmask(text)
def _get_label_image(text, font_color_tuple_bgr, background_color_tuple_bgr, font):
text_image = font.getmask(text)
shape = list(reversed(text_image.size))
bw_image = np.array(text_image).reshape(shape)

Expand Down Expand Up @@ -87,12 +85,18 @@ def add(image, left, top, right, bottom, label=None, color=None):
colors = [_rgb_to_bgr(item) for item in _COLOR_NAME_TO_RGB[color]]
color, color_text = colors

_cv2.rectangle(image, (left, top), (right, bottom), color, 2)
image_height, image_width, _ = image.shape
line_width_box = max(round(min(image_height, image_width) / 150), 2)

_cv2.rectangle(image, (left, top), (right, bottom), color, line_width_box)

if label:
_, image_width, _ = image.shape

label_image = _get_label_image(label, color_text, color)
font_height = max(round(min(image_height, image_width) / 40), 15)
font = ImageFont.truetype(_FONT_PATH, font_height)

label_image = _get_label_image(label, color_text, color, font)

label_height, label_width, _ = label_image.shape

rectangle_height, rectangle_width = 1 + label_height, 1 + label_width
Expand Down