cimo001 commited on
Commit
e4c2198
·
verified ·
1 Parent(s): d971d9b
Files changed (1) hide show
  1. PP-OCRv6_medium_rec/src/example.py +93 -0
PP-OCRv6_medium_rec/src/example.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ sys.dont_write_bytecode = True
3
+
4
+ import io
5
+ import math
6
+ import cv2
7
+ import numpy
8
+
9
+ from helper import onnxSessionBuild
10
+
11
+ pathModel = "./PP-OCRv6_medium_rec/"
12
+
13
+ imageHeightModel = 48
14
+ imageWidthModel = 320
15
+ imageWidthMax = 3200
16
+
17
+ characterList = ["blank"]
18
+
19
+ lineList = io.open(f"{pathModel}onnx/dictionary.txt", encoding="utf-8").read().split("\n")
20
+
21
+ for a in range(len(lineList)):
22
+ if lineList[a] != "":
23
+ characterList.append(lineList[a])
24
+
25
+ characterList.append(" ")
26
+
27
+ onnxSession = onnxSessionBuild(f"{pathModel}onnx/pp-ocrV6_medium_rec.onnx")
28
+
29
+ def imageResize(image):
30
+ imageHeight, imageWidth = image.shape[0:2]
31
+
32
+ ratioWidthHeight = max(imageWidthModel / float(imageHeightModel), imageWidth / float(imageHeight))
33
+
34
+ widthTarget = int(imageHeightModel * ratioWidthHeight)
35
+
36
+ if widthTarget > imageWidthMax:
37
+ widthTarget = imageWidthMax
38
+ widthResized = imageWidthMax
39
+ else:
40
+ widthResized = int(math.ceil(imageHeightModel * imageWidth / float(imageHeight)))
41
+
42
+ if widthResized > widthTarget:
43
+ widthResized = widthTarget
44
+
45
+ imageResized = cv2.resize(image, (widthResized, imageHeightModel))
46
+
47
+ tensor = imageResized.astype(numpy.float32).transpose((2, 0, 1)) / 255.0
48
+ tensor = (tensor - 0.5) / 0.5
49
+
50
+ tensorPadded = numpy.zeros((3, imageHeightModel, widthTarget), dtype=numpy.float32)
51
+ tensorPadded[:, :, 0:widthResized] = tensor
52
+
53
+ return numpy.expand_dims(tensorPadded, axis=0)
54
+
55
+ def inference(image):
56
+ tensor = imageResize(image)
57
+
58
+ tensorOutputList = onnxSession.run(None, {"x": tensor})
59
+
60
+ probability = tensorOutputList[0][0]
61
+
62
+ indexList = probability.argmax(axis=-1)
63
+ valueList = probability.max(axis=-1)
64
+
65
+ text = ""
66
+ scoreList = []
67
+
68
+ for a in range(len(indexList)):
69
+ if indexList[a] == 0:
70
+ continue
71
+
72
+ if a > 0 and indexList[a] == indexList[a - 1]:
73
+ continue
74
+
75
+ text += characterList[indexList[a]]
76
+
77
+ scoreList.append(float(valueList[a]))
78
+
79
+ score = 0.0
80
+
81
+ if len(scoreList) > 0:
82
+ score = float(numpy.mean(scoreList))
83
+
84
+ return {
85
+ "text": text,
86
+ "score": score
87
+ }
88
+
89
+ image = cv2.imread(sys.argv[1])
90
+
91
+ itemObject = inference(image)
92
+
93
+ print(f"{itemObject['score']:.6f} | {itemObject['text']}")