Tesseract OCR 및 Java 게이트웨이 사용

9475 단어 javatutorialocr
InterSystems IRIS는 Java 또는 .NET 구성 요소와 Object Script 소스 코드 내부의 해당 프레임워크를 사용하여 확장할 수 있습니다.

OCR Service라는 애플리케이션을 만들었습니다. Docker로 빌드하고 영어와 포르투갈어 방언으로 구성된 docker 인스턴스 내부에 Google Tesseract를 설치하지만 다른 100개 이상의 방언 설치가 가능합니다. Google Tesseract는 OCR을 사용하여 이미지를 수신하고 이미지에서 추출한 텍스트를 반환할 수 있습니다. 결과는 훈련된 방언으로 매우 좋습니다. 그러나 Tesseract가 자동차 번호판 및 기타 텍스트 패턴을 읽고 로드하여 텍스트를 추출하도록 훈련할 수 있습니다. Java에는 Tess4J라는 프레임워크가 있어 Java 호출 Tesseract 인스턴스 및 기능을 사용할 수 있습니다. 실행 참조:

OCR 작동

OCR 서비스에 대한 Java 코드를 참조하십시오.

private String extractTextFromImage(File tempFile) throws TesseractException {

  ITesseract tesseract = new Tesseract();
  tesseract.setDatapath("/usr/share/tessdata/"); //directory to trained models
  tesseract.setLanguage("eng+por"); // choose your language/trained model

  return tesseract.doOCR(tempFile); //call tesseract function doOCR() //passing the file to be processed with OCR technique

}




Tess4J는 ITesseract 인터페이스 클래스를 사용하여 Tesseract와의 모든 저수준 통신을 관리하고 사용할 OCR 모델을 설정하고 파일을 전달하는 doOCR()을 호출하기만 하면 됩니다. 쉬운!

운 좋게도 Tesseract와 상호 작용하기 위해 Tess4ObjectScript 프레임워크를 만들 필요가 없습니다. C 호출/콜아웃을 사용하면 가능하지만 Tesseract와 낮은 수준에서 대화하는 방법을 이해해야 합니다. 저는 Java Gateway를 사용하여 저장하는 것을 선호합니다. 많은 근무일!

Java Gateway를 사용하려면 IRIS OS 또는 도커 인스턴스에 Java를 설치하고 JAVA_HOME(Java가 설치된 위치를 알기 위한 변수)을 설정하고 CLASSPATH(Java 클래스, Tess4J Java 아카이브 및 기타 종속성을 가리키는 변수)를 설정해야 합니다. ObjectScript와 Java가 통신할 수 있도록 하는 프록시인 Java Gateway 인스턴스를 실행합니다. Java 및 Tesseract를 IRIS 인스턴스에 설치하려면 내 dockerfile 지침을 참조하십시오.

ARG IMAGE=store/intersystems/iris-community:2020.1.0.204.0
ARG IMAGE=intersystemsdc/iris-community:2020.1.0.209.0-zpm
ARG IMAGE=intersystemsdc/iris-community:2020.2.0.204.0-zpm
ARG IMAGE=intersystemsdc/irishealth-community:2020.3.0.200.0-zpm
ARG IMAGE=intersystemsdc/iris-community:2020.3.0.200.0-zpm
ARG IMAGE=intersystemsdc/iris-community:2020.3.0.221.0-zpm
ARG IMAGE=intersystemsdc/iris-community:2020.4.0.521.0-zpm
FROM $IMAGE

USER root   

WORKDIR /opt/irisapp
RUN chown ${ISC_PACKAGE_MGRUSER}:${ISC_PACKAGE_IRISGROUP} /opt/irisapp
USER ${ISC_PACKAGE_MGRUSER}

COPY  Installer.cls .
COPY  src src

COPY iris.script /tmp/iris.script

RUN iris start IRIS \
    && iris session IRIS < /tmp/iris.script \
    && iris stop IRIS quietly

USER root   

# Install Java 8 using apt-get from ubuntu repository
RUN apt-get update && \
    apt-get install -y openjdk-8-jdk && \
    apt-get install -y ant && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/* && \
    rm -rf /var/cache/oracle-jdk8-installer;

# Fix certificate issues, found as of 
# https://bugs.launchpad.net/ubuntu/+source/ca-certificates-java/+bug/983302
RUN apt-get install -y ca-certificates-java && \
    apt-get clean && \
    update-ca-certificates -f && \
    rm -rf /var/lib/apt/lists/* && \
    rm -rf /var/cache/oracle-jdk8-installer;

# Setup JAVA_HOME, to enable apps to know where the Java was installed
ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOME
ENV JRE_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JRE_HOME

# Setup classpath, to enable apps to know where java classes and java jar libraries was installed
ENV classpath .:/usr/irissys/dev/java/lib/JDK18/*:/opt/irisapp/*:/usr/irissys/dev/java/lib/gson/*
:/usr/irissys/dev/java/lib/jackson/*:/jgw/*
RUN export classpath
ENV CLASSPATH .:/usr/irissys/dev/java/lib/JDK18/*:/opt/irisapp/*:/usr/irissys/dev/java/lib/gson/*
:/usr/irissys/dev/java/lib/jackson/*:/jgw/*
RUN export CLASSPATH

USER root

ARG APP_HOME=/tmp/app

COPY src $APP_HOME/src

# Tess4J and another java libraries used, are into jgw folder and jgw folder is in the classpath
COPY jgw /jgw

# Copy our Java OCR program, packaged into a jar, to the jgw
COPY target/ocr-pex-1.0.0.jar /jgw/ocr-pex-1.0.0.jar  

COPY jgw/* /usr/irissys/dev/java/lib/JDK18/

# Install tesseract using ubuntu apt-get
RUN apt-get update && apt-get install tesseract-ocr -y

USER root

# Copy trained models eng and por to the models folder
COPY tessdata /usr/share/tessdata

# Install and config default OS locale - it is required to tesseract works fine
RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
 && locale-gen "en_US.UTF-8"
ENV LANG=en_US.UTF-8 \
    LANGUAGE=en_US:en \
    LC_ALL=en_US.UTF-8



ObjectScript 클래스가 상호 운용성 비즈니스 클래스 또는 오퍼레이션인 경우 Java Gateway 비즈니스 서비스(내 프로덕션에 JavaGateway 항목)를 설정하십시오.

Class dc.ocr.OcrProduction Extends Ens.Production
{

XData ProductionDefinition
{

<Production Name="dc.ocr.OcrProduction" LogGeneralTraceEvents="false">
  <Description></Description>
  <ActorPoolSize>2</ActorPoolSize>
  <Item Name="OcrService" Category="" ClassName="dc.ocr.OcrService" PoolSize="1" Enabled="true" 
Foreground="false" Comment="" LogTraceEvents="false" Schedule="">
  </Item>

  <Item Name="JavaGateway" Category="" ClassName="EnsLib.JavaGateway.Service" PoolSize="1" 
Enabled="true" Foreground="false" Comment="" LogTraceEvents="false" Schedule="">
    <Setting Target="Host" Name="ClassPath">.:/usr/irissys/dev/java/lib/JDK18/*:/opt/irisapp/*
:/usr/irissys/dev/java/lib/gson/*
:/usr/irissys/dev/java/lib/jackson/*:/jgw/ocr-pex-1.0.0.jar
</Setting>
    <Setting Target="Host" Name="JavaHome">/usr/lib/jvm/java-8-openjdk-amd64/</Setting>
  </Item>

</Production>

}



}

프로덕션에는 ObjectScript OCRService도 있습니다. 이 ObjectScript 클래스는 HTTP 멀티파트 요청에서 업로드된 파일을 수신하고 JavaGateway를 사용하여 Java 클래스를 로드하고 파일을 전달하고 OCR 프로세스에서 텍스트를 가져오므로 응답을 반환합니다. 보다:

Class dc.ocr.OcrService Extends Ens.BusinessService
{

// extends Ens.BusinessService to create a custom Business service using Object Script

// This class receive a file from a multipart http request and save 
// to the folder configured into folder parameter

// choose an adapter to get data from a source of data

// HTTP.InboundAdapter allows you get data from an http request

Parameter ADAPTER = "EnsLib.HTTP.InboundAdapter";

// custom parameter to allows production user set destination folder to multipart file uploaded 

Property Folder As %String(MAXLEN = 100);

// when you set parameter Folder to SETTINGS parameter, the production IRIS interface 
// create a field to the user fills
// so the user will inform host path for the uploaded file 

Parameter SETTINGS = "Folder,Basic";

// This method is mandatory to have a business service. It receives the multipart file into pInput 

// and returns a result to the caller using pOutput

Method OnProcessInput(pInput As %GlobalBinaryStream, pOutput As %RegisteredObject) As %Status
{
    //try to do the actions
    try {
        Set reader = ##class(%Net.MIMEReader).%New() //creates a MIMEReader to extract files 
//from multipart requests 
        Do reader.OpenStream(pInput) //reader open the file

        Set tSC = reader.ReadMIMEMessage(.message) //the reader put the file uploaded into a MIME Message
        //Get Header obtains headers from the request and the multipart file, like content-type or content 
//disposition the content disposition have 3 headers: Content-Disposition: form-data; name="file"; 
//filename="filename.ext". This split content-disposition header into 3 parts
        Set filenameHeader = $PIECE(message.GetHeader("CONTENT-DISPOSITION", .header),";",3) 
        //get filename header value
        Set filename = $EXTRACT(filenameHeader, 12, $LENGTH(filenameHeader)-1)
        //Headers are not more needed. It clean the header to remains only the file content to be saved
        Do message.ClearHeaders()

        //create a file object to save the multipart file
        Set file=##class(%Stream.FileBinary).%New()
        //points the file to folder informed into folder parameter, plus upload filename from header
        Set file.Filename=..Folder_filename 
        //save body message (the file content) to file object
        Do file.CopyFromAndSave(message.Body)

        // Connect a Gateway instance to server JavaGate on the host machine
        set GW = ##class(%Net.Remote.Gateway).%New()
        set st = GW.%Connect("127.0.0.1", "55555", "IRISAPP",,)
        //instantiate java ocr class
        set proxyOcr = ##class(%Net.Remote.Object).%New(GW,"community.intersystems.pex.ocr.OcrOperation")
        //call ocr method to get text from image
        set pResponse = proxyOcr.doOcr(file.Filename)
        //returns to the service
        Set pOutput = pResponse
        Set tSC=$$$OK

    //returns error message to the user
    } catch e {
        Set tSC=e.AsStatus()
        Set pOutput = tSC
    }

    Quit tSC
}

}




이제 IRIS는 이미지와 PDF에 대해 OCR을 수행할 수 있지만 JavaGateway 기능을 사용하면 많은 놀라운 일을 할 수 있습니다. 내 앱 코드에 대한 모든 세부 정보 보기: https://openexchange.intersystems.com/package/OCR-Service .

좋은 웹페이지 즐겨찾기