draw_bbox.py 2.0 KB
Newer Older
L
littletomatodonkey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import numpy as np
import cv2
littletomatodonkey's avatar
littletomatodonkey 已提交
18
from PIL import Image, ImageDraw, ImageFont
L
littletomatodonkey 已提交
19 20


littletomatodonkey's avatar
littletomatodonkey 已提交
21 22 23 24 25 26 27 28
def draw_bbox_results(image,
                      results,
                      input_path,
                      font_path="./utils/simfang.ttf",
                      save_dir=None):
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)
    draw = ImageDraw.Draw(image)
L
littletomatodonkey 已提交
29 30
    font_size = 18
    font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
littletomatodonkey's avatar
littletomatodonkey 已提交
31

D
dyning 已提交
32
    color = (0, 102, 255)
littletomatodonkey's avatar
littletomatodonkey 已提交
33

L
littletomatodonkey 已提交
34
    for result in results:
littletomatodonkey's avatar
littletomatodonkey 已提交
35 36 37 38 39 40
        # empty results
        if result["rec_docs"] is None:
            continue

        xmin, ymin, xmax, ymax = result["bbox"]
        text = "{}, {:.2f}".format(result["rec_docs"], result["rec_scores"])
L
littletomatodonkey 已提交
41
        th = font_size
L
littletomatodonkey 已提交
42 43
        tw = font.getsize(text)[0]
        # tw = int(len(result["rec_docs"]) * font_size) + 60
littletomatodonkey's avatar
littletomatodonkey 已提交
44
        start_y = max(0, ymin - th)
L
littletomatodonkey 已提交
45

L
littletomatodonkey 已提交
46 47 48 49
        draw.rectangle(
            [(xmin + 1, start_y), (xmin + tw + 1, start_y + th)], fill=color)

        draw.text((xmin + 1, start_y), text, fill=(255, 255, 255), font=font)
littletomatodonkey's avatar
littletomatodonkey 已提交
50 51 52

        draw.rectangle(
            [(xmin, ymin), (xmax, ymax)], outline=(255, 0, 0), width=2)
L
littletomatodonkey 已提交
53 54 55 56 57 58

    image_name = os.path.basename(input_path)
    if save_dir is None:
        save_dir = "output"
    os.makedirs(save_dir, exist_ok=True)
    output_path = os.path.join(save_dir, image_name)
littletomatodonkey's avatar
littletomatodonkey 已提交
59 60 61

    image.save(output_path, quality=95)
    return np.array(image)