opencv/text_recognition_crnn
1
1# This file is part of OpenCV Zoo project.2# It is subject to the license terms in the LICENSE file found in the same directory.3#4# Copyright (C) 2021, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved.5# Third party copyrights are property of their respective owners.6 7import numpy as np8import cv2 as cv9 10class PPOCRDet:11 def __init__(self, modelPath, inputSize=[736, 736], binaryThreshold=0.3, polygonThreshold=0.5, maxCandidates=200, unclipRatio=2.0, backendId=0, targetId=0):12 self._modelPath = modelPath13 self._model = cv.dnn_TextDetectionModel_DB(14 cv.dnn.readNet(self._modelPath)15 )16 17 self._inputSize = tuple(inputSize) # (w, h)18 self._inputHeight = inputSize[0]19 self._inputWidth = inputSize[1]20 self._binaryThreshold = binaryThreshold21 self._polygonThreshold = polygonThreshold22 self._maxCandidates = maxCandidates23 self._unclipRatio = unclipRatio24 self._backendId = backendId25 self._targetId = targetId26 27 self._model.setPreferableBackend(self._backendId)28 self._model.setPreferableTarget(self._targetId)29 30 self._model.setBinaryThreshold(self._binaryThreshold)31 self._model.setPolygonThreshold(self._polygonThreshold)32 self._model.setUnclipRatio(self._unclipRatio)33 self._model.setMaxCandidates(self._maxCandidates)34 35 self._model.setInputSize(self._inputSize)36 self._model.setInputMean((123.675, 116.28, 103.53))37 self._model.setInputScale(1.0/255.0/np.array([0.229, 0.224, 0.225]))38 39 @property40 def name(self):41 return self.__class__.__name__42 43 def setBackendAndTarget(self, backendId, targetId):44 self._backendId = backendId45 self._targetId = targetId46 self._model.setPreferableBackend(self._backendId)47 self._model.setPreferableTarget(self._targetId)48 49 def setInputSize(self, input_size):50 self._inputSize = tuple(input_size)51 self._model.setInputSize(self._inputSize)52 self._model.setInputMean((123.675, 116.28, 103.53))53 self._model.setInputScale(1.0/255.0/np.array([0.229, 0.224, 0.225]))54 55 def infer(self, image):56 assert image.shape[0] == self._inputSize[1], '{} (height of input image) != {} (preset height)'.format(image.shape[0], self._inputSize[1])57 assert image.shape[1] == self._inputSize[0], '{} (width of input image) != {} (preset width)'.format(image.shape[1], self._inputSize[0])58 59 return self._model.detect(image)60 