update
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import sysimport cv2import numpyfrom tokenizers import Tokenizer
sys.dont_write_bytecode = True
# Sourcefrom helper import onnxSessionBuild
pathModel = "./PP-FormulaNet_plus-L/"
imageSizeModel = 768
levelInk = 200
meanList = numpy.array([0.7931, 0.7931, 0.7931], dtype=numpy.float32)standardList = numpy.array([0.1738, 0.1738, 0.1738], dtype=numpy.float32)
countLayer = 8countStep = 1024sizeHidden = 512
tokenizer = Tokenizer.from_file(f"{pathModel}onnx/tokenizer.json")
idEnd = tokenizer.token_to_id("</s>")
onnxSessionEncoder = onnxSessionBuild(f"{pathModel}onnx/pp-formulaNet_plus-l_encoder.onnx")onnxSessionDecoder = onnxSessionBuild(f"{pathModel}onnx/pp-formulaNet_plus-l_decoder.onnx")
def imageResize(image): imageGray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY).astype(numpy.float32)
low = float(imageGray.min()) high = float(imageGray.max())
if high > low: imageInk = ((imageGray - low) / (high - low) * 255.0 < levelInk).astype(numpy.uint8)
inkX, inkY, inkWidth, inkHeight = cv2.boundingRect(cv2.findNonZero(imageInk))
image = image[inkY:inkY + inkHeight, inkX:inkX + inkWidth]
imageHeight, imageWidth = image.shape[0:2]
ratio = imageSizeModel / float(max(imageHeight, imageWidth))
widthResized = max(1, int(imageWidth * ratio)) heightResized = max(1, int(imageHeight * ratio))
padX = (imageSizeModel - widthResized) // 2 padY = (imageSizeModel - heightResized) // 2
imagePadded = numpy.zeros((imageSizeModel, imageSizeModel, 3), dtype=numpy.uint8) imagePadded[padY:padY + heightResized, padX:padX + widthResized] = cv2.resize(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), (widthResized, heightResized), interpolation=cv2.INTER_LINEAR)
return imagePadded
def tokenDecode(memory): idList = [idEnd]
buffer = numpy.zeros((countLayer, countStep, sizeHidden), dtype=numpy.float32)
while len(idList) < countStep: position = len(idList) - 1
tensorFeedObject = { "token": numpy.array([idList[position]], dtype=numpy.int64), "position": numpy.array(position, dtype=numpy.int64), "memory": memory, "buffer": buffer }
logit, state = onnxSessionDecoder.run(None, tensorFeedObject)
buffer[:, position] = state
idList.append(int(numpy.argmax(logit[0])))
if idList[position + 1] == idEnd: break
return idList
def inference(image): imagePadded = imageResize(image)
tensor = imagePadded.astype(numpy.float32) / 255.0 tensor = (tensor - meanList) / standardList tensor = numpy.expand_dims(tensor.transpose((2, 0, 1)), axis=0).astype(numpy.float32)
tensorOutputList = onnxSessionEncoder.run(None, {"image": tensor})
idList = tokenDecode(tensorOutputList[0])
return tokenizer.decode(idList, skip_special_tokens=True)
image = cv2.imread(sys.argv[1])
text = inference(image)
print(text)PP-FormulaNet_plus-L/src/example.pyAdded+102