Saturday, April 26, 2014

PowerShell functions using TessNet2 for OCR

#This script requires TessNet2 to be installed, run this script to install TessNet2. 

<#
     #Here is an example using these 2 functions to create a jpg from text then using TessNet2 to convert it back to text. 
     #Start by creating an image with text in it.  So we can use our OCR function on it.  
     Create-ImageFromText -FileName "$home\HelloWorld.jpg" -Text "Hello World From Tessnet2."
     #Uncomment this line if you want the image to pop up.
     & "$home\HelloWorld.jpg"
     $Result = Get-TextTextImage "$home\HelloWorld.jpg"
#>

Function Get-TextTextImage{
    [CmdletBinding()]
    Param(  [Parameter(Mandatory=$True,Position=1)] [string]$FileName)
    #Code was derived from the example on http://www.pixel-technology.com/freeware/tessnet2/
    $image = [System.Drawing.Bitmap]("$home\HelloWorld.jpg" )
    #The first time the Dll is used we have to deem it as same by unblocking-file.  No need to include it after the first run.
    Unblock-File "$Home\Programming\TessNet2\TessNetAssemblies\Release64\tessnet2_64.dll"
    [void][System.Reflection.Assembly]::LoadFrom("$Home\Programming\TessNet2\TessNetAssemblies\Release64\tessnet2_64.dll")
    $ocr = New-Object tessnet2.Tesseract
    ##############################the file location should point to the parent directory where the TessData pack was unzipped
    $void = $ocr.Init("$home\Programming\TessNet2\tessdata", "eng", $false)
    $result = $ocr.DoOCR($image, [System.Drawing.Rectangle]::Empty)
    $ocr.Dispose()
    $image.Dispose()
    return $result
}

Function Create-ImageFromText{
    [CmdletBinding()]
    Param(  [Parameter(Mandatory=$True,Position=1)] [string]$FileName,
            [Parameter(Mandatory=$True)]            [string]$Text)
     #Code to create an image from any given text was derived from Keith Hills reply on
    $TextToPutInImage = $Text
    $filename = $FileName 
    $length = $($TextToPutInImage.Length*30)
    Add-Type -AssemblyName System.Drawing
    $bmp = new-object System.Drawing.Bitmap $length ,90 
    $font = new-object System.Drawing.Font Consolas,24 
    $brushBg = [System.Drawing.Brushes]::Black 
    $brushFg = [System.Drawing.Brushes]::White 
    $graphics = [System.Drawing.Graphics]::FromImage($bmp) 
    $graphics.FillRectangle($brushBg,0,0,$bmp.Width,$bmp.Height) 
    $graphics.DrawString($TextToPutInImage,$font,$brushFg,10,10) 
    $graphics.Dispose() 
    $bmp.Save($filename,[ System.Drawing.Imaging.ImageFormat]::Jpeg) 
    $graphics.Dispose()
    $bmp.Dispose()
    $font.Dispose()
}

No comments:

Post a Comment