File size: 2,328 Bytes
44d0d80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import sys
import cv2
import numpy

sys.dont_write_bytecode = True

# Source
from helper import onnxSessionBuild

pathModel = "./Docling-Layout-Heron/"

imageSizeModel = 640

scoreThreshold = 0.5

labelList = [
    "caption",
    "footnote",
    "formula",
    "list_item",
    "page_footer",
    "page_header",
    "picture",
    "section_header",
    "table",
    "text",
    "title",
    "document_index",
    "code",
    "checkbox_selected",
    "checkbox_unselected",
    "form",
    "key_value_region"
]

onnxSession = onnxSessionBuild(f"{pathModel}onnx/docling-layout-heron.onnx")

def inference(imageRgb):
    resultList = []

    imageHeight, imageWidth = imageRgb.shape[0:2]
    imageResized = cv2.resize(imageRgb, (imageSizeModel, imageSizeModel), interpolation=cv2.INTER_LINEAR).astype(numpy.float32) / 255.0

    tensor = numpy.expand_dims(imageResized.transpose((2, 0, 1)), axis=0).astype(numpy.float32)

    tensorOutputList = onnxSession.run(None, {"pixel_values": tensor})

    scoreList = 1.0 / (1.0 + numpy.exp(-tensorOutputList[0][0].astype(numpy.float64)))
    boxList = tensorOutputList[1][0]

    for a in range(scoreList.shape[0]):
        for b in range(scoreList.shape[1]):
            if scoreList[a][b] < scoreThreshold:
                continue

            centerX, centerY, width, height = boxList[a]

            x1 = max(0.0, float(centerX - width / 2)) * imageWidth
            y1 = max(0.0, float(centerY - height / 2)) * imageHeight
            x2 = min(1.0, float(centerX + width / 2)) * imageWidth
            y2 = min(1.0, float(centerY + height / 2)) * imageHeight

            if x2 > x1 and y2 > y1:
                resultList.append({
                    "label": labelList[b],
                    "score": float(scoreList[a][b]),
                    "coordinate": [x1, y1, x2, y2]
                })

    resultList.sort(key=lambda itemObject: itemObject["score"], reverse=True)

    return resultList

image = cv2.imread(sys.argv[1])
imageRgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

itemList = inference(imageRgb)

for a in range(len(itemList)):
    coordinateList = []

    for b in range(len(itemList[a]["coordinate"])):
        coordinateList.append(int(round(itemList[a]["coordinate"][b])))

    print(f"{itemList[a]['score']:.6f} | {itemList[a]['label']} | {coordinateList}")