draw_bbox.py 1.9 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 29 30 31 32
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)
    font = ImageFont.truetype(font_path, 20, encoding="utf-8")

    color = (0, 255, 0)

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

        xmin, ymin, xmax, ymax = result["bbox"]
        text = "{}, {:.2f}".format(result["rec_docs"], result["rec_scores"])
        th = 20
        tw = int(len(result["rec_docs"]) * 20) + 60
        start_y = max(0, ymin - th)
        draw.rectangle(
            [(xmin + 1, start_y), (xmin + tw + 1, start_y + th)],
            outline=color)
L
littletomatodonkey 已提交
46

littletomatodonkey's avatar
littletomatodonkey 已提交
47 48 49 50
        draw.text((xmin + 1, start_y), text, fill=color, font=font)

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

    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 已提交
57 58 59

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