iContainersRead – примеры кода

< Назад на страницу продукта

Пример на C++

void test1Image(string pathToModels, string pathToImage)
{
    std::vector<std::string> modelFiles = getModelFiles(pathToModels);

    if (modelFiles.size() != 4)
    {
        std::cout << "Models not found! \n";
        return;
    }

    int error;
    iContainersObject iCO = iContainersInit((char*)modelFiles[0].c_str(),(char*)modelFiles[1].c_str(),
        (char*)modelFiles[2].c_str(), (char*)modelFiles[3].c_str(), license, &error);

    if (iCO == NULL || error != int(iCont::iContErrors::IC_OK))
    {
        std::cout << "Cann't init iContainersObject! Error = " << error << " \n";
        return;
    }

    iContainersSetting settings;
    settings.onlyFormatNumber = true;
    settings.correctSymbol = true;
    iContainersSettings(iCO, settings);

    Mat img = cv::imread(pathToImage);

    std::vector <cv::Mat> imgs(1, img);

    int result = iContainersRead(iCO, imgs);
    if (result != int(iCont::iContErrors::IC_OK))
        std::cout << "Inference problem! Error = " << result << " \n";

    std::vector<std::vector<NumberContainerResult>> numbers = iContainersGetResult(iCO);

    drawPlate(img, numbers, pathToImage + "_res.jpg");

    iContainersRelease(&iCO);
}

Пример определения класса на Python для работы с C++ библиотекой

# class for iContainersRead
import cv2
import numpy as np
import ctypes
import json
import logging

__name__ = "iCONTPY"
logger = logging.getLogger(__name__)

class iContRead(object):
    def __init__(self, dllPath):
        self.lib = ctypes.CDLL(dllPath)              
        # bool iContainersVersion(char* outBuf, int sizeBuf);
        self.iContainersVersion = self.lib.iContainersVersion
        self.iContainersVersion.restype = ctypes.c_bool
        self.iContainersVersion.argtypes = (ctypes.c_char_p,ctypes.c_int,)
        # iContainersInit(char* detectionModelPath, char* symbDetectionModelPath, 
	    #   char* classificationModelPath, char* recognitionModelPath, char* license, int* error);
        self.iContainersInit = self.lib.iContainersInit
        self.iContainersInit.restype = ctypes.c_void_p
        self.iContainersInit.argtypes = (ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,ctypes.c_char_p,
                                         ctypes.c_char_p,ctypes.POINTER(ctypes.c_int),)
        # bool iContainersReleaseP(iContainersObject * object);
        self.iContainersReleaseP = self.lib.iContainersReleaseP
        self.iContainersReleaseP.restype = ctypes.c_bool
        self.iContainersReleaseP.argtypes = (ctypes.c_void_p,)
        # bool iContainersSettingsJSON(iContainersObject object, char* json);
        self.iContainersSettingsJSON = self.lib.iContainersSettingsJSON
        self.iContainersSettingsJSON.restype = ctypes.c_bool
        self.iContainersSettingsJSON.argtypes = (ctypes.c_void_p,ctypes.c_char_p,)
        # int iContainerAddImage(iContainersObject object, const char* imageBytes, long sizeImage);
        self.iContainerAddImage = self.lib.iContainerAddImage
        self.iContainerAddImage.restype = ctypes.c_int
        self.iContainerAddImage.argtypes = (ctypes.c_void_p,ctypes.c_char_p,ctypes.c_long,)
        # int iContainerInference(iContainersObject object);
        self.iContainerInference = self.lib.iContainerInference
        self.iContainerInference.restype = ctypes.c_int
        self.iContainerInference.argtypes = (ctypes.c_void_p,)
        # int iContainerInferenceOnlyNumber(iContainersObject object);
        self.iContainerInferenceOnlyNumber = self.lib.iContainerInferenceOnlyNumber
        self.iContainerInferenceOnlyNumber.restype = ctypes.c_int
        self.iContainerInferenceOnlyNumber.argtypes = (ctypes.c_void_p,)
        # int iContainersGetResultJSON(iContainersObject object, char* outBuf, int sizeBuf);
        self.iContainersGetResultJSON = self.lib.iContainersGetResultJSON
        self.iContainersGetResultJSON.restype = ctypes.c_int
        self.iContainersGetResultJSON.argtypes = (ctypes.c_void_p,ctypes.c_char_p,ctypes.c_int,)

        self.icont = None
        
        size = 1000
        p = ctypes.create_string_buffer(size)
        self.iContainersVersion(p,size)
        logger.info(p.value.decode("ascii"))

    def __del__(self):        
        if not self.icont is None:
            if self.iContainersReleaseP(self.icont):
                logger.info("Object iContRead deleted")

    def init(self,detection,symb,classification,recognition,license) -> bool:         
        er = ctypes.c_int()
        self.icont = self.iContainersInit(bytes(detection,'ascii'),bytes(symb,'ascii'),bytes(classification,'ascii'),
                                          bytes(recognition,'ascii'),bytes(license,'ascii'),ctypes.byref(er))
        if self.icont != None:
            logger.info("Object iContRead loaded")
            return True
        logger.error("Object iContRead not loaded: "+ str(er))
        return False

    def setSettings(self, settings) -> bool:
        s = json.dumps(settings)
        if self.iContainersSettingsJSON(self.icont,bytes(s,'ascii')):
            logger.info("iContainersSettingsJSON installed")
            return True
        logger.error("iContainersSettingsJSON not loaded")
        return False

    def putImage(self, img) -> bool:
        img_str = cv2.imencode('.bmp', img)[1].tostring() 
        res = self.iContainerAddImage(self.icont,img_str,len(img_str))
        if res == 0:
            logger.info("Image added")
            return True
        logger.error("Image not added. Error = "+str(res))
        return False

    def inference(self) -> bool:
        res = self.iContainerInference(self.icont)
        if res == 0:
            logger.info("Inference true")
            return True
        logger.error("Inference error = "+str(res))
        return False

    def inferenceNumber(self) -> bool:
        res = self.iContainerInferenceOnlyNumber(self.icont)
        if res == 0:
            logger.info("Inference true")
            return True
        logger.error("Inference error = "+str(res))
        return False

    def getResult(self,code = "ascii") -> str:       
        size = 10000
        p = ctypes.create_string_buffer(size)
        if self.iContainersGetResultJSON(self.icont,p,size) != 0:
            return ""        
        return p.value.decode(code)

Пример вызова из Python

def iContImage(imgPath, code):  
    if iCont.init(models[0],models[1],models[2],models[3],lic):
        if iCont.setSettings(settings):        
            img = cv2.imread(imgPath)
            if iCont.putImage(img):
                if iCont.inference():
                    s = iCont.getResult(code)
                    print(s) # JSON 
                    if (len(s) > 1):
                        d = json.loads(s)                        
                        if d.get("images"):
                            drawImage(img,"out.png",d["images"][0])

if __name__ == "__main__":
    script_dir = os.path.dirname(os.path.abspath(__file__))
    dll_path = os.path.join(script_dir, 'iContainersReadCPU.dll')
    iCont = ic.iContRead( dll_path  )
    
    settings = {
        "correctSymbol":1,	    
        "onlyFormatNumber":0
    }

    models = ["data/models/detectionnumber.model",
          "data/models/detection_symb.model",
          "data/models/classification.model",
          "data/models/rec_infer.model"]

    lic = ""    

    with open("lic.key", "r") as f:
        # итерация по строкам
        for line in f:
            lic = line.strip()
            break

    iContImage("test_img.jpg","utf8")
Прокрутить вверх
Этот сайт использует сервис веб-аналитики «Яндекс.Метрика», который применяет cookie-файлы и технологии локального хранилища. Это помогает нам анализировать, как вы взаимодействуете с сайтом: например, сколько времени провели на странице и какие кнопки нажимали. Собранные данные полностью обезличены. Продолжая пользоваться сайтом, вы соглашаетесь с использованием cookie-файлов и технологий «Яндекс.Метрики» в соответствии с настоящим уведомлением. Политика безопасности
Принять