view.py 2.16 KB
Newer Older
yuguo-Jack's avatar
yuguo-Jack committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Copyright (c) 2022 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 cv2
import json
import numpy as np


def view_ocr_result(img_path, bboxes, opath):
    image = cv2.imread(img_path)
    for char_bbox in bboxes:
        x_min, x_max, y_min, y_max = char_bbox
        cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 0, 255), 1)
    cv2.imwrite(opath, image)


def _highlight_bbox(img, bbox):
    x = bbox[0]
    w = bbox[1] - x
    y = bbox[2]
    h = bbox[3] - y
    sub_img = img[y : y + h, x : x + w]
    colored_rect = np.zeros(sub_img.shape, dtype=np.uint8)
    colored_rect[:, :, 2] = 255
    colored_rect[:, :, 1] = 255
    res = cv2.addWeighted(sub_img, 0.5, colored_rect, 0.5, 1.0)
    img[y : y + h, x : x + w] = res


def highlight_ans(source_img_path, output_img_path, ans_bbox):
    image = cv2.imread(source_img_path)
    for bbox in ans_bbox:
        _highlight_bbox(image, bbox)
    cv2.imwrite(output_img_path, image)


def highlight_img(source_img_path, output_img_path):
    image = cv2.imread(source_img_path)
    height = image.shape[0]
    width = image.shape[1]
    bbox = [0, width - 1, 0, height - 1]
    _highlight_bbox(image, bbox)
    cv2.imwrite(output_img_path, image)


if __name__ == "__main__":
    res_path = "./data/decode_res.json"
    result = {}
    with open(res_path, "r", encoding="utf-8") as f:
        line = f.readline()
        result = json.loads(line.strip())

    img_path = "../OCR_process/demo_pics/demo_{}.png".format(result["img_id"])
    img_save_path = "../answer.png"
    highlight_ans(img_path, img_save_path, result["predict_bboxes"])
    print("extraction result has been saved to answer.png")